• Save
Java servlet life cycle - methods ppt
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Java servlet life cycle - methods ppt

on

  • 7,645 views

Java servlet life cycle - methods ppt.

Java servlet life cycle - methods ppt.
In this PPT you will find all things about java servlet including life cycle and methods

Statistics

Views

Total Views
7,645
Views on SlideShare
7,325
Embed Views
320

Actions

Likes
11
Downloads
0
Comments
0

3 Embeds 320

http://java2all.com 305
http://playjava.wordpress.com 10
http://plus.url.google.com 5

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Java servlet life cycle - methods ppt Presentation Transcript

  • 1. History of web application    There are 4 components involved  Webpage  Website  Web Browser  Web Server Earlier, a web page merely displayed static content (html) But, today’s web application provides interactive experience as if users are talking face to face (dynamic content).  Chatting  Online shopping  Online reservation  and the list keeps on increasing………….
  • 2. Web Application  What is web application?   Application that runs on WWW is known as web application. How does it work? Request Response Client Server
  • 3. Common Gateway interface   It was the first technique for creating dynamic content. With CGI, server passes the request to CGI program and the o/p is sent to the client Request Response Client Server
  • 4. Limitations  It creates a new process to run CGI program.  It requires time and significant server resources.  Number of request cannot be handled concurrently. Process for CGI 1 Process for CGI 2 Process for CGI 1 Request for CGI 1 Request for CGI 2 Request for CGI 1 Server
  • 5. Limitations  It creates a single process for each CGI program.  It requires time and significant server resources. Request for CGI 1 Process for CGI 1 Request for CGI 2 Request for CGI 1 Process for CGI 2 Server
  • 6. Definition   Servlet is a Java class that extends the functionality of web server. Eg:  Mail Server  Servlet is a class that performs virus scan to attached files.
  • 7. Benefits   Only one copy of servlet is loaded into JVM. Each request begins a new thread to servlet than a process.    Saves time Response time increases It is scalable JVM Request for Servlet 1 Request for Servlet 2 Request for Servlet 1 Servlet1 thread Servlet2
  • 8. User Web Browser J2EE Server Java Servlet EJB Web server Database
  • 9. Http   HttpRequest Client ---------------------------------Server GET/index.html/HTTP1.1 Client----------------------------------Server User-Agent:Microsoft IE Blank line is sent   Client -------------- HttpResponse ----------Server Client --------------------------------Server HTTP1.1 200 OK Server: Apache Tomcat Content-Type: text/html  Blank line is sent Client --------------------------------Server Index.html
  • 10. Servlet Implementation  Servlet use classes and interfaces from 2 packages  javax.servlet   It contains classes to support generic protocol javax.servlet.http  It extends classes in servlet package to add HTTP specific functionality.
  • 11. javax.servlet package javax.servlet ServletConfig Servlet ServletRequest ServletResponse java.lang Object Exception GenericServlet ServletException MyServlet Unavailable Exception
  • 12. javax.servlet.http package javax.servlet javax.servlet.http Servlet ServletRequest ServletResponse HttpServletRequest HttpServletResponse java.lang Object Exception GenericServlet ServletException HttpServlet
  • 13. Servlet API             Servlet Interface GenericServlet Class HttpServlet Class HttpServletRequest Interface HttpServletResponse Interface Cookie Class HttpSession Interface SingleThreadModel Interface ServletException class UnavailableException class ServletContext interface ServletConfig Interface
  • 14. Servlet Interface  Every servlet must implements the javax.servlet.Servlet interface.  It can implement in 2 ways:   Directly implementing interface Extending any of 2 classes:   javax.servlet.GenericServlet javax.servlet.http.HttpServlet
  • 15. Methods      init() service() destroy() getServletInfo() getServletConfig()
  • 16. service()  Syntax:  public abstract void service(ServletRequest req,ServletResponse res) throws ServletException,IOException  It is called whenever the request is made It must be overridden in servlet It receives request via ServletRequest and Sends response via Servlet Response  
  • 17. GenericServlet  It provides basic implementation of the servlet interface for protocol-independent servlets.  It has init() and destroy() methods to perform setup and clean-up tasks.  service() method is defined abstract and must be overidden.
  • 18. GenericServlet subclass request service() response
  • 19. HttpServlet  It is an abstract class that is used for developing HTTP servlets.  It does not override the service() method.  It overrides doGet() to handle GET requests and doPost() to handle POST requests
  • 20. HttpServlet subclass request doGet() service() response doPost() Web Server
  • 21. Methods        service() doGet() doPost() doDelete() doOption() doPut() doTrace()
  • 22. doGet() or doPost()  protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException  protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
  • 23. HttpServletRequest interface             getParameter() getParameterNames() getParameterValues() getHeaders() getQueryString() getRemoteAddr() getRemoteHost() getAttribute() setAttribute() getAttributeNames() getCookies() getSession()
  • 24. getParameter()  Syntax:   Public abstract String getParameter(String name) Description:    Returns value of the named parameter as a string Returns null if the parameter does not exist or empty string. Eg:  String name=req.getParameter(“t1”) //t1 is name of text box
  • 25. getParameterValues()  Syntax:   Public String[] getParameterValues(String name) Description    It returns all the values of name parameter as an array of string object Returns null if he parameter does not exist. Eg:  String values []=req.getParameterValues(String name)
  • 26. getParameterNames()  Syntax:   Public Enumeration getParameterNames() Description:    It returns all the parameter names as an enumeration of string It returns an empty enumeration if the servlet has no parameters. Eg:  Enumeration en=req.getParameterNames();
  • 27. Enumeration Methods  hasMoreElements()    Public boolean hasMoreElements() Returs true if and only if this enumeration object contains at least one more element to provide; false otherwise. Eg: while(en.hasMoreElements()) { }  nextElement()     Public Object nextElement() Returns the next element of this enumeration if this enumeration object has at least one more element to provide. Throws: NoSuchElementException - if no more elements exist. Eg: en.nextElement()
  • 28. getHeader()  Syntax:  Public String getHeader(String name) Description  Returns the value of the named header as a string  It takes name of header and retrieve the value of header Eg: String val=req.getHeader(name of header) 
  • 29. getHeaderNames()  Syntax:   Public Enumeration getHeaderNames() Description: It Returns the names of all the headers as an enumeration of string objects. Eg: Enumeration en=req.getHeaderNames() While(en.hasMoreElements()) { String name=(String)enum.nextElement(); String val=req.getHeader(name); } 
  • 30. getQueryString()  Syntax:   Public String getQueryString() Description:   It returns the raw query string of the request or null if no query string is send. Eg:  req.getQueryString()
  • 31. getRemoteAddr()  Syntax:   public String getRemoteAddr() Description:    Returns IP address of the client machine as a string. It could be remote address of proxy server also Eg:  String addr=req.getRemoteAddr()
  • 32. getRemoteHost()  Syntax:   public String getRemoteHost() Description:    Returns host name of the client machine as a string. It could be remote name of proxy server also Eg:  String addr=req.getRemoteHost()
  • 33. getAttribute()  Syntax:   Public Object getAttribute(String name) Description   It returns the value of a server specific attribute for the request. It returns null if the server does not support the named attribute.
  • 34. getAttributeNames()  Syntax:   Public Enumeration getAttributeNames() Description  It returns all the attribute names as an Enumeration of string, supported by web server or null if not attributes are specified
  • 35. setAttribute()  Syntax:   Public void setAttribute(String name.String value) Description   It set new attribute of server It takes 2 argumnets Name  Value The new value is appended to the Enumeration returned by getAttributeNames() method 
  • 36. Cookies  Cookie is a bit of information sent by a webserver to a browser that can be later read back from that browser.  Cookie class  javax.servlet.http.Cookie class is provided by servlet API
  • 37. Creating cookie     Cookie can be created with cookie() constructor public cookie(String name,String value) It creates new cookie with initial name and value. Eg:  Cookie ck = new Cookie(“emailid”,”abc”);
  • 38. Sending a cookie   Sending - Response A servlet can send a cookie to client by passing a cookie object to    addCookie() method of HttpServletResponse interface. public void addcookie(Cookie obj); Eg:  res.addCookie(ck);
  • 39. Reading a cookie     Reading –request A servlet retrieves cookies by calling getCookies() method of HttpServletRequest inerface Public Cookie[] getCookies(); Returns array of cookie object sent by browser or null if no cookies are sent
  • 40. Attributes of Cookies Attribute Description Name Name of cookie Value Value of cookie Version Set version of cookie Domain Domain name that will read a cookie MaxAge Expiry date in seconds -ve value indicates default, it will expire when browser is closed 0 indicates to delete immediately Path Path where cookie is sent Secure Boolean value true/false comment Comment about it Attributes can be set and retrieved by setXXX() and getXXX() method of Cookie class
  • 41. HttpServletResponse        getWriter() setContentType() addCookie() encodeURL() sendRedirect() setHeader() setStatus()
  • 42. getWriter()  Syntax:   Public abstract PrintWriter getWriter() throws IOException Description    Returns PrintWriter for writing character-based response data. Eg: PrintWriter out=res.getWriter();
  • 43. setContentType()  Syntax:   Public abstract void setContentType(String type) Description    It sets the content type of the response to be specified type. It sets the Content-type HTTP header res.setContentType(“text/html”)
  • 44. addCookie  Syntax:   Public abstract void addCookie(Cookie ck) Description:    Add the specified cookie to the response. Browsers accept only 20 cookies per site,300 total per user and size cookie’s size 4096 bytes. res.addCookie(ck)
  • 45. sendRedirect()  Syntax:   Public abstract void sendRedirect(String location) throws IOException Description:     Redirects the response to the specified location. The location must be absolute URL Eg: res.sendRedirect(“http://localhost:8084/test”)
  • 46. encodeURL()  Syntax:   Public abstract String encodeURL(String url) Description:  Returns specified URL encoded to include the session information.  String url=res.encodeURL(“http://localhost:8084/test?id=123”) res.sendRedirect(url); 
  • 47. setHeader()  Syntax:   Public abstract void setHeader(String name,String value) Description:    Sets the value of the named header as String. If header has already been set, the new value overwrites the previous one. res.setHeader(“Set-Cookie”,”ck”);
  • 48. setStatus()  Syntax:    Public abstract void setStatus(int sc) Public abstract void setStatus(int sc, String sm) Description:     It sets HTTP status code. The code can be specified using numeric value or by using SC_XXX codes. res.setStatus(404) res.setStatus(404,”Sorry ! File not found”)
  • 49. SC_XXX codes  Constants defined in HttpServletResponse     SC_OK SC_NOT_FOUND SC_INTERNAL_SERVER_ERROR SC_BAD_REQUEST 200 404 500 400
  • 50. Session  Session is period between user login and logout. Login Session logout Session data should be available in all the pages after user logins until he logs out.
  • 51. Session Tracking Approaches   HTTP is stateless protocol To maintain the state of user 4 approaches are used     Hidden form fields URL Rewriting Cookies Session API
  • 52. Hidden Fields    Hidden fields are not displayed on browser. They are sent to the sever when the form is submitted Eg:    <form action=“login”> <input type=“hidden” name=“t1” value=“abc”> </form> String name=req.getParameter(“t1”);
  • 53. Pros and Cons  Advantages    They can always be used They are supported by browser Disadvantage  They only work for sequence of forms
  • 54. URL Rewriting  With this method, URL can be dynamically modified or rewritten to include extra information.  http://localhost:8084/test http://localhost:8084/test/123 http://localhost:8084/test?id=123   URL extra path extra parameter
  • 55. Limitation    Limit to size of URL (255 char) It cannot be used if method used by target URL is POST Parameter name collision might occur
  • 56. Cookies  Advantages    Efficient, easy way to implement session Customize cookie Disadvantages    Browser doesn’t support cookies Deleted by the client Modified by the client
  • 57. Session API  Session tracking is efficient method of handling session  Every user of a site is associated with a javax.servlet.http.HttpSession object  A servlet uses its request object’s getSession() method to retrieve the current session
  • 58. getSession()  Syntax:   Public HttpSession getSession(boolean create) Description  It returns the current session associated with the user.  If user has not created session, it will create if true is passed as an argument or returns null if false is passed  To enable session, this method must be called at least once before any output is written.  HttpSession ses=req.getSession(true);
  • 59. HttpSession           setAttribute() getAttribute() getAttributeNames() removeAttribute() getId() getCreationTime() getLastAccessedTime() setMaxInactiveInterval() isNew() invalidate()
  • 60. setAttribute()  Syntax:   Public abstract void setAttribute(String name,Object value) Description:   Binds the specified object value under specified name in the session. Eg:  ses.setAttribute(“id”,”abc”)
  • 61. getAttribute()  Syntax:   Public abstract object getAttribute(String name) Description:   Returns the object bound in the session under the specified name or null if session is invalid. String val=(String)ses.getAttribute(id); // output abc
  • 62. getAttributeNames()  Syntax:   Public abstract Enumeration getAttributeNames() Description   Return the enumeration of all names of attributes or null if not attributes are set Eg: Enumeration en=ses.getAttributeNames() While(en.hasMoreElements()) { String name=(String)en.nextElement() }
  • 63. removeAttribute()  Syntax:     Public abstract void removeAttribute(String name) Description Removes the object bound to the specified name or does nothing if there is no binding, Eg:  ses.remove Attribute(id);
  • 64. invalidate()  Syntax:   Public abstract void invalidate() Description:   Causes the session to be immediately invalidated. All objects stored in the session are unbound.
  • 65. getId()  Syntax:   Public abstract String getID() Description   Returns the unique string identifier assigned to this session. Eg:  String id=ses.getID();
  • 66. getCreationTime()  Syntax:   Public abstract long getCreationTime() Description  Returns the time at which the session was created, as a long representing the number of milliseconds since epoch.
  • 67. getLastAccessTime()  Syntax:   Public abstract long getLastAccessTime() Description  Returns the time at which the client last sent a request with this session, as a long representing the number of milliseconds since epoch.
  • 68. setMaxInactiveInterval()  Syntax:     public void setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should never timeout. Eg:  ses.setMaxInactiveInterval(300);
  • 69. HTTP Request Methods   doDelete() Syntax:  protected void doDelete(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException  The delete method is used to delete the documents directly from the server
  • 70.   doPut() Syntax:   protected void doPut(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException It is used to put the document’s directly to the sever
  • 71.   doTrace() Syntax:   protected void doTrace(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException It is used as debugging aid- it returns to the client exact contents of its request
  • 72.   doOption() Syntax:   protected void doOption(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException It is used to ask the sever which methods it supports or what options are available on the server
  • 73. SingleThreadModel interface   It is defined in javax.servlet package Syntax:   Public interface SingleThreadModel{ } If a servlet implements this interface,  The server ensures that each instance of the servlet handles only one service request at a time.
  • 74. ServletException  Exception  ServletException  UnavailableException
  • 75. ServletException It is a class which handles generic exception thrown by servlet encountering difficulties.  Class Summary Public class ServletException extends Exception { public ServletException(); public ServletException(String message); } 
  • 76.   Constructs a new ServletException with an optional descriptive message. If message is specified, it can be retrieved using getMessage() method.
  • 77. UnaviableException   A servlet can throw an unavailable exception at any time to indicate that it is not available to service client requests There are 2 types of unavailability   Permanent Temporary
  • 78. Class Summary  public class UnavailableException extends ServletException { public UnavailableException (int sec,Servlet servlet, String msg) public UnavailableException(Servlet sevlet,String msg) public Servlet getServlet() public int getUnavailableSeconds() public boolean isPermanent() }
  • 79. Methods  Public Servlet getServlet()   Public int getUnavailableSeconds()   Returns the servlet that threw this exception Returns number of seconds for which servlet will be unavaiable. A –ve value indicated permanent unavailability. Public boolean isPermanent()  Returns true if the servlet is unavailable indefintely
  • 80. Servlet Life Cycle  Servlet consist of following cycle  Create and initialize the servlet   Handle zero or more service calls from clients   init() doGet() or doPost() Destroy the servlet and then garbage collect it  destroy()
  • 81. Init() Syntax:  Public void init(ServletConfig config) throws ServletException  It is used to initialize variables and objects that are used throughout the java Servlet.  The servletConfig object supplies a servlet with information about its initialization (init parameters) available to servlet and not with request
  • 82. ServletConfig() interface   It is used to pass initialization and context information to servlets Methods    public abstract String getInitParameter(String name) public abstract Enumeration getInitParameterNames() Public abstract ServletContext getServletContext()
  • 83. doGet() or doPost()  protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException  protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
  • 84. Destroy()    Public void destroy() Called when servlet is preparing to unload a servlet. Used to clean up any outstanding resources (database connection, threads, file handle)
  • 85. What is Context?  In terms of Servlet, a context is a directory that contains a single web application       a set of related html files JavaBeans JSP files and/or servlets The terms context and webapp are pretty much synonymous. A context directory may contain one or more servlets. The ServletContext interface defines methods that can be used in non-request specific manner. ServletContext sc=this.getServletContext();
  • 86. ServletContext         getContext() getServerInfo() getInitParameter() getInitParameterNames() getAttribute() setAttribute() removeAttribute() getRequestDispatcher()
  • 87. getContext()  Syntax:   Public ServletContext getContext(String url) Description    Returns the context object for the resource at the specified path on the server. The path must be relative with / ServletContext sc1=sc.getContext()
  • 88. getServerInfo  Syntax:   Public String getServerInfo() Description    It returns a string object containing information about the sever on which servlet is running. It will contain server name and version Apache tomcat/6.0.18
  • 89. getInitParameter()  Syntax:   Public String getInitParameter(String name) Description:   Context parameters can be used in entire web application not in specific servlet unlike init parameter of Config object. It returns a string containing the value of specified parameter or null if no init parameter exists.
  • 90. getInitParameterNames()  Syntax:   Public Enumeration getInitParameterNames() Description:  It returns a Enumeration containing the initialization parameters associated with invoking ServletContext object.
  • 91. setAttribute()  Syntax:   Public abstract void setAttribute(String name,Object value) Description:   Binds the specified object value under specified name in the context Eg:  sc.setAttribute(“id”,”abc”)
  • 92. getAttribute()  Syntax:   Public abstract object getAttribute(String name) Description:   Returns the object bound in the context under the specified name. String val=(String)sc.getAttribute(“id”); // output abc
  • 93. removeAttribute()  Syntax:     Public abstract void removeAttribute(String name) Description Removes the object bound to the specified name or does nothing if there is no binding, Eg:  sc.removeAttribute(“id”);
  • 94. Attributes  Request  Attributes are objects associated with a request. Attributes may be set by the a servlet to communicate information to another servlet (via the RequestDispatcher).  Session  A servlet can bind an object attribute into an HttpSession implementation by name. Any object bound into a session is available to any other servlet that handles a request identified as being a part of the same session.  Context  A servlet can bind an object attribute into the context by name. Any attribute bound into a context is available to any other servlet that is part of the same Web application.
  • 95. getRequestDispatcher()  Syntax:   Public RequestDispatcher getRequestDispatcher(String url) Description  It reuturns a RequestDispatcher object located at the specified path. The path must be relative beginning with /  requestDispatcher rd=sc.getRequestDispatcher(“/test”);
  • 96. RequestDispatcher() interface  Defines an object that receives requests from the client and sends them to any resource on the server. A single client request can be passed to many resoruce such as:     servlet HTML file JSP file Methods   forward() include()
  • 97. forward()  Syntax:  public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException  Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.  forward should be called before the response has been committed to the client.  If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.  rd.forward(req,res)
  • 98. include()  Syntax:  public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException  Includes the content of a resource (servlet, JSP page, HTML file) in the response.  The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.  rd.include(req, res);