Java Servlets

Servlets
  • Java servlets are programs that run on webserver.
  • Servlets are server side programmes That run on web or Application server And act as a middle between requests coming from a web browser and database on application server.
  • A web server response can be static or dynamic
    • Static: HTML document is typed from the file system and returned to the client
    • Dynamic: HTML document is required from the file system and returned to the client.
  • Java servlets are a technology for producing dynamic server responses.
    • Servlet - Is a class instantiated by the server to produce a dynamic response.
  • Servlet is a Java program on server used to provide some functionality.
  • While applets are embedded into web pages and run on client side.
  • To run servelet client may not require java.
  • Servlets act as middle layer between requests coming from web browsers and databases or applications on the HTTP server.
  • A servlet container uses Java Virtual Machine to run servlet code as requested by a Web server.
  • A servlet dynamically loads a module requested by a webserver.
  • A servlet is a server side technology Which is used to
    • Handle the client request
    • Process the request
    • Generate dynamic response.

  • A servlet code is loaded into memory only once.
  • After servlet is loaded, handling new request is only a matter of calling a service method.
  • This separates servlet from CGI where program is loaded each time request is made.
  • In case of servlets if there are n-threads only single copy of servlets is loaded.
  • On deployment instance of Servlet is created.
  • Designed to provide dynamic functionality to any internet server service.
    • HTTP servers
    • SMTP servers
    • FTP servers
  • Opposite of Applets
    • Extend functionality of a web browser
    • Extend functionality of an internet service
  • Server - Centric Java Objects
    • Developed using OO principles
    • Synchronous in nature
    • Conceptually stateless
  • Simplify server development
    • Hide protocol details
    • Hide network communication details
    • Hide server implementation
  • Achieved through definition of :
    • Servlet API
    • Servlet Lifecycle
      • Loading and instantiation
        • When server Starts servlet class is loaded in memory and servlet object is created.
        • Call only once.
      • Initialisation
        • Init() method is called to initialise the servlet
        • Called only once.
      • Request handling
        • Service() method is invoked here when client initiates a request To the servlet.
        • It handles or serve the client request.
        • Each time client initiates a request, a thread is created to invoke service method.
      • Destroy
        • Destroy method is called.
        • When the server is shut down, this toy method is executed and servlet object will be deleted.
        • Executed only once in life cycle.
    • Servlet Development Requirements
    • Servlet Packaging and Configuration
  • For secure communication, we use Https.
  • Servlet is an Interface.
  • We can create a servlet Either by implementing servlet interface or by Inheriting the servlet classes.
  • We have to create a deployment descriptor file also called as “web.xml”.
    • We provide servlet mapping and configuration in web.xml
    • We create Tags like Web-app, servlet-mapping and servlet which helps us to configure servlet.
    • We create web.XML in WEB – INF folder.
    • We can also use annotations instead of web.xml to create servlets in latest Java versions.
    • Uses
      • Servlet configuration
      • Filters configuration
      • JSP file configuration
      • Listeners configuration
      • Error Page configuration
      • Welcome file configuration.
    Servlet API
    • The servlet API is based on two primary packages :
      • javax.servlet - Generic
      • javax.servlet.http - HTTP Centric
    Servlet Types
    • HTTP Servlet
      • Has Protocol
      • Has a client managed state
      • More easy to develop
      • Has a lifecycle
      • Requires Runtime configuration
      • Extends development cycle
      • Has a manual chaining access
      • Has a request access
      • Has a Response access
    • Generic Servelet
      • May have a protocol
      • May have a client managed state
      • More difficult to develop
      • Has a lifecycle
      • Is somewhat errorprone
      • Requires runtime configuration
      • Extends development cycle
      • Has manual chaining access
      • Has a request access
      • Has a Response access
    • Filter Servelet
      • May have a protocol
      • May have a client managed state
      • Easy to develop
      • Has a lifecycle
      • Has a runtime configuration
      • Implements development cycle
      • Auto chaining process
      • Has a request access
      • Has a Response access
    Advantages
    1. Efficient
      1. A servlet code is loaded into memory only once.
      2. After the code is loaded handling new request is a matter of calling service method.
      3. For all the threads only a single copy is loaded.
    2. Portable
      1. Servlets in Java are independent of machine architecture.
    3. Robust
      1. Because servlets are developed with access to entire JDK, servlet support several capabilities they are very powerful.
      2. There is a garbage collector to prevent memory leaks.
      3. Servlets can also maintain information from request to request.
    4. Extensible
      1. Servlets are developed into java they can be extended into new objects that are better than the previous one.
    5. Secure
      1. Since servlets run on server side they are secure.They inherit security provided by the web server.
    Servlet Architecture 
    • Servlets are created by extending Generic servelet or HTTPServelet class available in package javax.servelet and javax.servelet.http.
    • Servlet service() method is called by server.
    • The other 2 methods are init() and destroy().
      • init() method is called when servlet is loaded into memory.
      • destroy() method is called when servlet is unloaded from memory.


    Layered Architecture of a Servlet Application
    • The outermost layer is user's web browser that makes TCP connections to the tomcat web container through which it sends HTTP request messages.
    • The second layer is Tomcat which parses the incoming HTTP request messages into instances of the HTTPServletRequest class and then passes these objects to the doGet and doPost methods of an appropriate servlet based on the request URL.
    • The third layer is the presentation layer which is comprised of servlets and JSP scripts.
      • The servlets act as controllers because their service methods(doGet,doPost) act as entry points into the web application.
      • The servlets may look into one or more business objects through persistence services and invoke business functionality on them.
      • After business functions are completed the servlets invoke javascripts passing to them references to appropriate domain objects.
      • The jsp's generate HTML to display to user an appropriate view.
    Generic Servlet
    1. Generic Servlet is the core class in javax.servlet package.
    2. Generic Servlet is used to create servlets by extending it.
    3. Generic Servlet provides methods like service(),init() and destroy() in Servlet Config interface.
    4. Generic Servlet Is a class that implements servlet interface.
    5. When we want to create protocol independent object, we extend generic servlet.
    6. A protocol independent servlet is a servlet that can handle requests from different network protocols such as HTTP, HTTPS, FTP and more.
    Http Servlet
    1. Http Servlet inherits basic servlet functionality by extending Generic Servlet.
    2. It is used when we want HTTP specific methods and we want to use request-response object.
    3. Http Servlet must override methods such as service(),doGet(),doPost().
      1. Service method receives 2 parameters HttpServletRequest and HttpServletResponse.
        1. HttpServletRequest Methods
          1. getParameter(String name)
            1. Returns the value of the request parameter specified by the name.
          2. getCookies()
            1. Returns an array Of cookie objects representing the cookies included in the request.
          3. getSession(boolean create)
            1. Return the current session associated with the request or create a new one if create is true.
          4. getMethod()
            1. Returns the HTTP method of the request such as GET, POST, PUT, DELETE et cetera.
          5. getAttribute(String name)
            1. Returns the value of the name attribute as an object.
          6. setAttribute(String name,Object Value)
            1. Binds object to a given attribute name in the request scope.
          7. getHeader(String name)
            1. Returns the value of the specified HTTP header.
          8. getHeaderNames()
            1. Returns an enumeration Of all the header names Sent with the request.
        2. HttpServletResponse Methods
          1. getWriter()
            1. Returns the PrinterWriter object That can be used to send character text to the client.
          2. setContentType(String type)
            1. Set the MIME type of the response.
          3. setContentLimit(int len)
            1. Set the length of content being returned in the response.
          4. sendRedirect(String Location)
            1. Redirects The client to a Different URL.
          5. sendError(int sc, String msg)
            1. Sends error response To the client with the specified status code and message.
          6. addCookie(Cookie cookie)
            1. Add a cookie to the response.
          7. setStatus(int sc)
            1. Search the status code of the response.
          8. setHeader(String name,String value)
            1. Set the value of specified response header.
          9. addHeader(String name,String value)
            1. Adds a response header With the given name and value.
      2. The doGet() Method is called in response to an Http Get Request, used to send client data.
        1. Get values from the server on the basis of a Criteria.
        2. Manipulates something into server or Store something into server.
      3. The doPost() is called in response to an HTTP POST request from HTML form.
    4. HTTP servlet Is a class that inherits Generic Servlet.
    5. Some of the commonly used HTTP methods are
      1. GET
        1. The GET is used to revive information from the given server using Given URI. Requests Using GET should only with retrieve data and should have no other effect on the data.
        2. GET method, sends data via resource URL and thus it is not secured.
        3. GET is slightly faster because The values are sent in the header
        4. We can send very less data in case of GET Request because it adds the data to the URL and the length of a URL is limited.
        5. GET request can be cached.
        6. GET request can be bookmarked.
      2. HEAD
        1. Same as GET, but transfers the status line and header section only.
      3. POST
        1. A POST Request is used to send data to the server, for example, customer information, file upload et cetera using HTML forms.
        2. POST method, sends data via HTTP massage body And is more secure.
        3. POST is slightly slow because the values are sent in the request body, in the format that content type specifies.
        4. We can send huge amount of data in case of POST request, there is no restriction.
        5. POST request cannot be cached
        6. POST request cannot be bookmarked.
      4. PUT
        1. Replaces All current representation Off the target resource with the uploaded Content.
      5. DELETE
        1. Removes all current representations of the target resource given by a URI.
    Servlet Annotations Configuration
    • Use annotation @WebServlet(“/url”) above the class Which Extends HTTPServlet.
    • No need to use Web.xml file
      Servlet Development Requirements
      • Follows semantics of any java object
        • Can have a constructor
        • Can have member variables
        • Can have methods
        • Can use other objects and classes
        • Typically no static methods
      • Required yet flexible class hierarchy
        • Must be considered a javax.servelet.servelet
        • Can also be specialization of other types
      Servlet Development Lifecycle
      • Create client; Typically HTML form
      • Build Servelet
        • Accept request data
        • Perform Business Logic
        • Return Response Data
      • Compile servelet
      • Package servelet
      • Deploy servelet
      • Test servelet
      Packaging Servelets
      • Servelets are packaged within WAR files.
      • WAR file must contain application artifacts and configuration information
        • Servelet application artifact is a class
        • Servelet configuration is found in web.xml
      • WAR filename becomes context.
      Running a Servlet on Webserver
        • To run a servlet on webserver
          • Create a webfolder test(application folder)
          • Create a folder WEB-INF in it
            • Inside this folder create a file web.xml
              •  <web-app>  
                 <servlet>  
                 <servlet-name>example</servlet-name>  
                 <servlet-class>DateServlet</servlet-class>  
                 </servlet>  
                 <servlet-mapping>  
                 <servlet-name>example</servlet-name>  
                 <url-pattern>/date</url-pattern>  
                 </servlet-mapping>  
                 </web-app>  
                
            • Create folder classes
              • Inside classes folder add the compiled servlet class.
          • Compile the servlet using following code
            • javac -cp %pathToTomcat%/lib/servlet-api.jar HelloServlet.java
        Servlet JDBC Example
          • Create a new Dynamic Web Project in Eclipse
          • Generate web.xml(deployment descriptor)
          • Add new servelet class in Java Resources in src.
          • Add Html files in Web Content Folder.
          • Include server runtime in your build path or include "servelet-api.jar" from your server libraries.
          • Add Mysql Connector jar to java build path entries.
          • Add Mysql Connector jar to Deployment Assembly=>Add java build path entries=>select entry.
          Adding values to the table
          Following is a sample code of adding values to a table emp with 2 columns name and dept.We have created a form servlet for this as follows.
            1:  import java.io.IOException;  
            2:  import java.io.PrintWriter;  
            3:  import java.sql.Connection;  
            4:  import java.sql.DriverManager;  
            5:  import java.sql.SQLException;  
            6:  import java.sql.Statement;  
            7:  import javax.servlet.RequestDispatcher;  
            8:  import javax.servlet.ServletException;  
            9:  import javax.servlet.annotation.WebServlet;  
            10:  import javax.servlet.http.HttpServlet;  
            11:  import javax.servlet.http.HttpServletRequest;  
            12:  import javax.servlet.http.HttpServletResponse;  
            13:  /**  
            14:   * Servlet implementation class formservlet  
            15:   */  
            16:  @WebServlet("/formservlet")  
            17:  public class formservlet extends HttpServlet   
            18:  {  
            19:       private static final long serialVersionUID = 1L;  
            20:    /**  
            21:     * Default constructor.   
            22:     */  
            23:    public formservlet() {  
            24:      // TODO Auto-generated constructor stub  
            25:    }  
            26:       /**  
            27:        * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)  
            28:        */  
            29:       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
            30:            // TODO Auto-generated method stub  
            31:            response.getWriter().append("Served at: ").append(request.getContextPath());  
            32:       }  
            33:       /**  
            34:        * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  
            35:        */  
            36:       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
            37:            try  
            38:            {  
            39:                 response.setContentType("text/html");  
            40:                 PrintWriter out=response.getWriter();  
            41:                 try  
            42:                 {  
            43:                      Class.forName("com.mysql.jdbc.Driver");  
            44:                      String jdbcUrl="jdbc:mysql://localhost:3306/jdbc_test";  
            45:                      String uname="root";  
            46:                      String pwd="";  
            47:                      Connection connection=null;  
            48:                      connection=DriverManager.getConnection(jdbcUrl, uname, pwd);  
            49:                      Statement statement=connection.createStatement();  
            50:                      String x=request.getParameter("ename");  
            51:                      String y=request.getParameter("dept");  
            52:                      String sql="insert into emp (name,dept) values ('"+x+"','"+y+"')";  
            53:                      statement.executeUpdate(sql);  
            54:                      out.println("Record Added Successfully");  
            55:                      RequestDispatcher rd=request.getRequestDispatcher("/form.html");  
            56:                      rd.include(request,response);  
            57:                 }   
            58:                 catch (ClassNotFoundException e)   
            59:                 {  
            60:                      out.println("Class Not Found");  
            61:                      e.printStackTrace();  
            62:                 }   
            63:            }  
            64:            catch (SQLException e)   
            65:            {  
            66:                 e.printStackTrace();  
            67:                 throw new RuntimeException("Cannot connect the database!",e);  
            68:            }  
            69:       }  
            70:  }  
            

            Html file which Posts to form servlet
             <!DOCTYPE html>  
             <html>  
             <head>  
             <meta charset="ISO-8859-1">  
             <title>Insert title here</title>  
             </head>  
             <body>  
             <form action="http://localhost:8080/demojdbc/formservlet" method="POST">  
             <label>Name:</label>  
             <input type="text" name="ename">  
             <label>Dept:</label>  
             <input type="text" name="dept">  
             <input type="submit">  
             </form>  
             </body>  
             </html>  
            

            In the above code we capture data in doPost method of servlet we are performing following steps
            • In line no 43 we check for the presence of Mysql Driver class and create its instance.
              • This class is provided by vendor Mysql.
              • The jar file name is mysql-connector.jar.
              • We are also using an exception for this class in case class is not found.
            • In line no 48 we create a jdbc connection and pass our MYSQL parameters to it.
            • In line no 52 we create an Insert statement using our request parameters.
            • In line no 53 we will update the records by passing our statement in method executeUpdate.
              • This method executes the Insert/Update statement.
            Fetching values from the table
            Next let us fetch values from the table based on department.We have created a report servlet for this as follows.
             import java.io.IOException;  
             import java.io.PrintWriter;  
             import java.sql.Connection;  
             import java.sql.DriverManager;  
             import java.sql.ResultSet;  
             import java.sql.SQLException;  
             import java.sql.Statement;  
             import javax.servlet.ServletException;  
             import javax.servlet.annotation.WebServlet;  
             import javax.servlet.http.HttpServlet;  
             import javax.servlet.http.HttpServletRequest;  
             import javax.servlet.http.HttpServletResponse;  
             /**  
              * Servlet implementation class reportservlet  
              */  
             @WebServlet("/reportservlet")  
             public class reportservlet extends HttpServlet {  
                  private static final long serialVersionUID = 1L;  
               /**  
                * @see HttpServlet#HttpServlet()  
                */  
               public reportservlet() {  
                 super();  
                 // TODO Auto-generated constructor stub  
               }  
                  /**  
                   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)  
                   */  
                  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
                       // TODO Auto-generated method stub  
                       response.getWriter().append("Served at: ").append(request.getContextPath());  
                  }  
                  /**  
                   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  
                   */  
                  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
                       // TODO Auto-generated method stub  
                       try  
                       {  
                            response.setContentType("text/html");  
                            PrintWriter out=response.getWriter();  
                            try  
                            {  
                                 Class.forName("com.mysql.jdbc.Driver");  
                                 String jdbcUrl="jdbc:mysql://localhost:3306/jdbc_test";  
                                 String uname="root";  
                                 String pwd="";  
                                 Connection connection=null;  
                                 connection=DriverManager.getConnection(jdbcUrl, uname, pwd);  
                                 Statement statement=connection.createStatement();  
                                 String z=request.getParameter("dept");  
                                 String sql="Select * from emp where dept='"+z+"'";  
                                 out.println("<h1>Employee Details</h1>");  
                                 ResultSet rs=statement.executeQuery(sql);  
                                 out.println("<table border='2'>");  
                                 out.println("<tr>");  
                                 out.println("<th>ENAME</th>");  
                                 out.println("<th>DEPT</th>");  
                                 out.println("</tr>");  
                                 while(rs.next())  
                                 {  
                                      String ename=rs.getString("name");  
                                      String dept=rs.getString("dept");  
                                      out.println("<tr>");  
                                      out.println("<td>"+ename+"</td>");  
                                      out.println("<td>"+dept+"</td>");  
                                      out.println("</tr>");  
                                 }  
                                 out.println("</table>");  
                            }  
                            catch (ClassNotFoundException e)   
                            {  
                                 out.println("Class Not Found");  
                                 e.printStackTrace();  
                            }  
                       }  
                       catch (SQLException e)   
                       {  
                            e.printStackTrace();  
                            throw new RuntimeException("Cannot connect the database!",e);  
                       }  
                  }  
             }  
            1. In the above file again we are creating a connection to database.
            2. We have created a create statement.
            3. This time we are performing an executeQuery instead of executeUpdate.
              1. We are executing the statement using executeQuery.
            4. We are storing response in a resultset we can also use a rowset here.
            5. Next we are iterating our resultset and printing each row.
            Html which posts to report servlet
             <!DOCTYPE html>  
             <html>  
             <head>  
             <meta charset="ISO-8859-1">  
             <title>Insert title here</title>  
             </head>  
             <body>  
             <form action="http://localhost:8080/demojdbc/reportservlet" method="POST">  
             <label>Department:</label>  
             <input type="text" name="dept">  
             <input type="submit">  
             </form>  
             </body>  
             </html>  
            

            Session Management
            1. The session identifier is stored internally by Tomcat.
              1. We can associate objects with this identifier by accessing the Session object with the client.
                1. This is done by calling getSession() on HttpServletRequest object that is passed into the doGet() or doPost() methods of our servlets.
              2. We associate objects with sessions by storing a name/value pair within the session, which acts like a map data structure.
              3. When the request comes in for a protected resource, we look for their id in the session object, if id is there then we know that this session and its data belongs to the particular client.
            Security Filter
              1. Security filter is used to enforce authorization policies for the web application.
                1. Users can access resources to which they are authorized too.
              2. Servlet filter is a component that is configured to preprocess and postprocess requests that are processed by the servlets.
                1. We place security code in servlet filter thus we separate security related code from the code that implements application functionality, which adheres to the separation of concerns principle.
              3. This filter implements Filter interface.
              4. The do filter method for a filter is called for every requested resource.
              5. To create exceptions from filters such as for login page, signup page,XSS feeds we call the dofilter() on the chain object of FilterChain class
                1. This chain object is passed as a parameter in doFilter.
                2. The chain object represents the chain of processors that will be used for incoming requests.
                3. After calling this dofilter() we return because the servlet would have processed the request.
              6. Following snippet implements tells web container about filter from web.xml file 
                      <filter>  
                           <filter-name>security-filter</filter-name>  
                           <filter-class>org.javaimplant.newsfeed.Filters.SecurityFilter</filter-class>  
                      </filter>  
                      <filter-mapping>  
                           <filter-name>security-filter</filter-name>  
                           <url-pattern>/*</url-pattern>  
                      </filter-mapping>  
                

                Filter Class
                 package org.javaimplant.newsfeed.Filters;  
                 import java.io.IOException;  
                 import javax.servlet.Filter;  
                 import javax.servlet.FilterChain;  
                 import javax.servlet.FilterConfig;  
                 import javax.servlet.ServletException;  
                 import javax.servlet.ServletRequest;  
                 import javax.servlet.ServletResponse;  
                 import javax.servlet.http.HttpServletRequest;  
                 import javax.servlet.http.HttpServletResponse;  
                 import javax.servlet.http.HttpSession;  
                 import org.apache.log4j.Logger;  
                 public class SecurityFilter implements Filter {  
                      private Logger logger = Logger.getLogger(this.getClass());  
                      @Override  
                      public void init(FilterConfig filterConfig) throws ServletException {  
                           // TODO Auto-generated method stub  
                      }  
                      @Override  
                      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  
                                throws IOException, ServletException {  
                           logger.debug("doFilter()");  
                           HttpServletResponse resp = (HttpServletResponse) response;  
                           HttpServletRequest req = (HttpServletRequest) request;  
                           String servletPath = req.getServletPath();  
                           if (servletPath.equals("/login"))  
                           {  
                                chain.doFilter(req, resp);  
                                return;  
                           }  
                           if (servletPath.equals("/news.rss"))   
                           {  
                                chain.doFilter(req, resp);  
                                return;  
                           }  
                           HttpSession session = req.getSession();  
                           Long userId = (Long) session.getAttribute("userId");  
                           if (userId != null)  
                           {  
                                chain.doFilter(req, resp);  
                                return;  
                           }  
                           resp.sendRedirect("login");  
                      }  
                      @Override  
                      public void destroy() {  
                           // TODO Auto-generated method stub  
                      }       
                 }  
                
                Working of Servlet

                • Advantages of servlets over CGI
                  • Performance is significantly better
                  • Servlets execute within the address space of a web server.(It is not necessary to create separate process to handle each client request)
                  • Servlets are platform independent because they are written in Java.
                  • Java security manager on the server en forces, a set of restrictions to protect the resources on server machine.
                  • The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, db or other software via the sockets and remote machines.
                SendRedirect() vs RequestDispatcher
                • SendRedirect() method is used to redirect the response to another resource that is to a servlet or JSP or HTML etc.
                  • It is a method of HTTPServletResponse
                  • URL Changes to that of new resource
                  • It is used for external request redirection.
                  • It redirects a Request to a different application or url.
                • Request Dispatcher
                  • The request dispatcher interface is used to dispatch the request to another resource(Servlet or JSP or HTML) Within same application.
                  • URL does not Changes in this case.
                  • It is used for internal request redirection
                  • It forward or includes the request to Some application or URL.
                  • It has two methods forward() and include().
                  • It does not change the URL on the browser.
                Http Session
                • We use session to maintain user’s identity.
                • To access a value On different pages.
                • We use HTTPServletRequest Interface to get the object of HTTP session.
                • Some of the commonly used methods of HTTP session oared
                  • setAttribute(“key”,value)
                  • getAttribute(“key”)
                  • removeAttribute(“key”)
                  • invalidate();
                • Delete a session
                  • <session-timeout> tag in web.xml
                  • Close browser
                  • Use invalidate method.

                No comments:

                Post a Comment