Saturday, November 23, 2013

Understanding Servlet


  1. Servlet act as a middle layer between a request coming from a Web browser and application on the server.
  2. Advantages:
    1. Execute within the Web server address space so no need to create a separate process to handle each client request.
    2. Platform-independent as written in Java
  3. Servlet can be created using javax.servlet and javax.servlet.http packages
    1. Servlet interface – defines life cycle methods
public interface Servlet {
    public void init(ServletConfig config) throws
ServletException;
    public ServletConfig getServletConfig();
    public void service(ServletRequest req, ServletResponse
      res) throws ServletException, IOException;
    public String getServletInfo();
    public void destroy();
}
    1. GenericServlet class – provides Java Servlet API
public abstract class GenericServlet implements Servlet,
      ServletConfig, Serializable {
   public GenericServlet() { ... }
   public void destroy() { ... }
   public String getInitParameter(String name) { ... }
   public Enumeration getInitParameterNames() { ... }
   public ServletContext getServletContext() { ... }
   public String getServletInfo() { ... }
   public void init(ServletConfig config) throws
      ServletException { ... }
   public void init() throws ServletException { ... }
   public void log(String msg) { ... }
   public void log(String message, Throwable t) { ... }
   public abstract void service(ServletRequest req,
ServletResponse res) throws ServletException,
IOException;
   public String getServletName() { ... }
}
    1. HttpServlet class – provides method for handling HTTP-specific request like GET (doGet) and POST (doPost).
public abstract class HttpServlet extends GenericServlet {
   protected void doGet(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ... }
   protected long getLastModified(HttpServletRequest req) {
      ... }
   protected void doHead(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ... }
   protected void doPost(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ...}
   protected void doPut(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ...}
   protected void doDelete(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ...}
   protected void doOptions(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ...}
   protected void doTrace(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ...}
   private static Method[] getAllDeclaredMethods(Class c)
      { ...}
   protected void service(HttpServletRequest req,
      HttpServletResponse resp) throws ServletException,
      IOException { ...}
   private void maybeSetLastModified(HttpServletResponse
      resp, long lastModified) { ...}
   public void service(ServletRequest req, ServletResponse
      res) throws ServletException, IOException { ...}
}
  1. Servlet lifecycle
    1. Initialization– Servlet is initialized by calling init() method. It is called only once when Servlet is first created. This happens when user invoke a URL corresponding to the Servlet.
    2. Service - For subsequent calls it creates a new thread and had off job to appropriate doXXX() method through service() method.
    3. Destory – Servlet is destroy at the end of lifecycle. destroy() method is called.
Summary: One time initialization (if needed) goes in init(), all processing is done in doXXX() method, clean up (if necessary) is does in destroy() method.
  1. Architecture Diagram


                                                
  1. Sample Application
    1. Create Servlet Class
       public class HelloServlet extends HttpServlet {   
             private Integer classVariable = 1;    
         private Integer servletInitilizationValue = 100;  
         @Override  
         public void init() throws ServletException {  
           servletInitilizationValue ++;  
         }  
         protected void processRequest(HttpServletRequest request,   
                 HttpServletResponse response)  
             throws ServletException, IOException {  
           Integer processVariable = 0;  
               classVariable*=2;  
           response.setContentType("text/html;charset=UTF-8");  
           PrintWriter out = response.getWriter();  
           try {  
             out.println("<html>");  
             out.println("<head>");  
             out.println("<title>Servlet HelloServlet</title>");        
             out.println("</head>");  
             out.println("<body>");  
             out.println("<h1>Servlet HelloServlet at " +   
                      request.getContextPath() + "</h1>");  
             out.println("<h2>processVariable: " +   
                      processVariable++);  
             out.println("<h2> servletInitilizationValue: " +   
                      servletInitilizationValue);  
                 out.println("<h2>classVariable: " + classVariable);  
             out.println("</body>");  
             out.println("</html>");  
           } finally {        
             out.close();  
           }  
         }  
         @Override  
         public void destroy() {  
           System.out.println("Destroying");  
         }  
         @Override  
         protected void doGet(HttpServletRequest request,   
                 HttpServletResponse response)  
             throws ServletException, IOException {  
           processRequest(request, response);  
         }  
         @Override  
         protected void doPost(HttpServletRequest request, HttpServletResponse response)  
             throws ServletException, IOException {  
           processRequest(request, response);  
         }  
       }  
      

Output:
- For first call servletInitilizationValue will display 101 and for subsequent call it remains 101 because servletInitilizationValue++ is called only once for first time.
- processVariable will be 0 for all call even we are doing processVariable++ because every request will get there own copy of processVariable
- But classVariable will always print even number for each call because only one instance of HelloServlet is created and instance variable is shared by all request.
- From these output we can see that as Servlet is not thread safe we can safe the data if put in method level instead of instance level.

    1. Map URL to Servlet class
Add Servlet definition and mapping in web.xml file
 <servlet>  
     <servlet-name>HelloWorld</servlet-name>  
     <servlet-class>HelloWorld</servlet-class>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>HelloWorld</servlet-name>  
     <url-pattern>/HelloWorld</url-pattern>  
   </servlet-mapping>  
   
  1. Some request header
-    accept
-    accept-charset
-    accept-encoding
-    accept-language
-    content-length
-    cookie
-    host
-    if-modified-since
-    if-unmodified-since
-    referrer
-    user-agent
  1. Some of the request object methods
-    getParameter(Strring parameterName): Get value of the parameter
-    getParameterValues(): Get multiple values for same parameter (e.g checkbox)
-    getParameterNames(): Get list of all parameters.
-    getCookies()
-    getSession()
-    getLocale()
-    getAuthType()
-    getCharacterEncoding()
-    getContentType()
-    getContextPath()
-    getHeader(String name)
-    getPathInfo()
-    getProtocol()
-    getQueryString()
-    getServletPath(): part of URl that calls the JSP.
-    getRemoteAddr(): client address
-    getRemoteHost(): client host name
-    getRemoteUser(): clinet login user
-    isSecure()
-    getContentLength()
-    getServerPort(0: port number which receive this request
  1. Some response header
-    Allow
-    Cache-control
-    Connection
-    Content-encoding
-    Content-language
-    Content-length
-    Content-type
-    Expires
-    Last-modified
-    Location
-    Refresh
-    Retry-after
-    Set-cookie
  1. Some of response object methods
-    encodeRedirectURL(String)
-    encodeURL(String)
-    addCookie(Cookie cookie)
-    sendError(…)
-    sendRedirect(String)
-    setBufferSize(int)
-    setCharacterEncoding(String)
-    setContentLength(int)
-    setContentType(String)
-    setHeader(String name, String value)
-    setLocale(Locale)
-    setStatus(int)
  1. HTTP Staus codes
- 100: continue
- 101: Switching protocols
- 2xx: Successful
- 3xx: Redirection
- 4xx: Client Error
- 5xx: Server Error
  1. Related technology is Filters

No comments: