Java Servlet - Java

  • Basic
    • Acts as middle layer between a request from client to database
    • Java
  • Architecture
    • Different threads can be created for each request instead of sending multiple requests
    • Java
  • Life Cycle
    • Servelet interface declares all life cycles methods
    • GenericServelet is an abstract class which provides based Servelet implementations except service() method
    • HttpServlet is abstract class which provides http specific methods like doGet(), etc
    • Java
    • init()
      • Called only once, Servlet is created
      • Code
            public void init() throws ServletException {
                // Statements
            }
        
    • service()
      • Called whenever a request is made, Handles request
      • Checks the http request type and calls the required method
            public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
                // Statements
            }
        
      • doGet()
            public void doGet(HTTPServletRequest request, HTTPServletResponse response) throws ServletException, IOException {
                // Statements
            }
        
    • destroy()
      • Called only once, Servlet is destroyed
      • Code
            public void destroy() throws ServletException {
                // Statements
            }
        
  • Code
    • main.java
          import javax.servlet.*
          import javax.servlet.http.*
          public class NamasteDunia extends HttpServlet {
              private string message;
              public void init() throws ServeletException {
                  message = "Namaste Dunia";
              }
              public void doGet(HTTPServeletRequest request, HTTPServeletResponse response) throws ServeletException, IOException {
                  response.setContentType("text/html");
                  printWriter out = response.getWriter();
                  out.println("<h1>"+message+"</h1>");
              }
              public void destroy() throws ServeletException {
                  // Statements
              }
          }
      
    • web.xml
          <servlet>
              <servlet-name>NamasteDunia</servlet-name>
              <servlet-class>NamasteDunia</servlet-class>
          </servlet>
          <servlet-mapping>
              <servlet-name>NamasteDunia</servlet-name>
              <url-pattern>/NamasteDunia</url-pattern>
          </servlet-mapping>
      
  • ServeletConfig object is created by web container for each Servelet during initialization
    • Should be placed within tag
  • ServeletContext is created while deploying web application
    • Should be placed outside tag
  • RequestDispatcher
    • Provides facility to dispatch client's request to another web resource and to include the response of another web resource
    • Forward():
          RequestDispatcher
          rd=request.getRequestDispatcher("resource")
          rd.forward(request, response);
      
    • Include():
          RequestDispatcher
          rd=request.getRequestDispatcher("resource")
          rd.include(request, response);
      
  • HTML Forms
    • request.getParameter("name") => Get a value from a parameter
    • request.getParameterValues() => When parameter returns multiple values or appearns more than once
    • request.getParameterNames() => Gives complete list of all the parameters
  • Session Tracking
    • Way to store client data throught the session
    • Techniques
      • URL Techniques
      • Hidden Form Field
      • Cookies
        • Types
          • Non-persistent
            • Valid only for single session => Removed each time browser is closed
          • Persistent
            • Valid only for multiple session
        • Code
          • Cookie c = new Cookie("key", "value"); => Create Cookie
          • c.setMaxAge(N); => Set max age
          • response.addCookie(c); => Send into HTTP header
          • Cookie c[] = request.getCookies(); => Get all the cookies
      • HttpSession
        • Servelet creates the object and generates a unique id along with client information
        • Response will contain the generated session id
        • Methods
          • getId(), setAttribute(String name, Object value), getAttribute(String name), invalidate()
  • Servelet Filter
    • Does pre and post processing with Request and Response
    • Code
          <filter>
              <display-name>MyFilter</display-name>
              <filter-name>MyFilter</filter-name>
              <filter-class>com.MyFilter</filter-class>
          </filter>
      
Share: