Java Servlets

This is a short introduction to get you start and experience with Java servlets. For more information, please refer to Sebesta book.

Overview

What is a servlet?

  • A Java object that responds to HTTP requests.
  • Runs inside a servlet container (or sometimes called a servlet engine).
Image: General view of servlet and servlet container

What does a servlet container do?

Image: What does servlet container do?

Servlet lifecycle

Image: Servlet lifecycle

How to implement Java servlets?


Image: Generic servlet and http servlet

Implement the interface javax.servlet.Servlet by extending either the class GenericServlet (javax.servlet.GenericServlet) or HttpServlet (javax.servlet.http.HttpServlet).

Servlet methods

  • init() -- called when servlet starts to initialize services
  • service() -- called to process requests
    • The entry point for the servlet (after init() is called)
    • Called from the servlet container
    • Decide what type of request is coming in and then call the appropriate mehod
      • HTTP GET requests -- doGet()
      • HTTP POST requests -- doPost()
  • destroy() -- called by container before servlet process ends
    • To clean up the state of the servlet
    • Informing another application the servlet is stopping
  • getServletConfig() -- servlet can access information about servlet container
    • Return a ServletConfig object (which stores information about the servlet's configuration)
  • getServletInfo() -- servlet container can access information about servlet
    • Author
    • Creation date
    • Description
    • Usage
    • ...

Simple servlet example

      import javax.servlet.*;
      import javax.servlet.http.*;
      import java.io.*;
          
      public class Hello extends HttpServlet
      {
         public void doGet (HttpServletRequest req,
                            HttpServletResponse res)
                     throws servletException, IOException
         { 
            res.setContentType (“text/html; charset=‘UTF-8’”);
            PrintWriter out = res.getWriter ();
             
            out.println (“<html>”);
            out.println("   <head>");
            out.println("      <title>Servlet example</title>");
            out.println("   </head>");
            out.println("   <body>");
            out.rintln("       <p>My first servlet<g;/p>");
            out.println("   </body>");
            out.println("</html>");
            out.close();
         }
      }
      
http://apps-swe432.vse.gmu.edu:8080/swe432/servlet/offutt.Hello

HttpServletRequest

  • Represent the HTTP request a browser sends to a web application. Thus, anything the browser may send is accessible via the HttpServletRequest
  • The request parameters are parameters that are sent from the browser along with the request, typically as part of the URL or as part of the body of an HTTP request.

      method call: 
         System.out.println (“aString”);
      servlet parameters transmission: 
         http://www example com/servlet/PrintThis?arg=aString
    
    
      multiple parameters are separated by '&'
         http://www.example.com/servlet/PrintThis?color=red&arg=Mike&age=39
          
      order of parameters does not matter     
         http://www.example.com/servlet/PrintThis?arg=Hello&color=red&age=39    
          
      empty string
         http://www.example.com/servlet/PrintThis?arg=&color=red&age=39    
      
  • To access the parameters from the HttpServletRequest object
      http://www.example.com/servlet/PrintThis?arg=Hello&color=red&age=39
      
      protected void doGet( HttpServletRequest request,
                            HttpServletResponse response)
                     throws ServletException, IOException 
      {
         String param1 = request.getParameter("arg");
         String param2 = request.getParameter("color");
         String param3 = request.getParameter("age");
      }        
      
    Image: Servlet parameter example

  • Most browsers give a warning before submitting POST data for the second time -- to avoid duplicate submissions and updates
        The page you are trying to view contains POSTDATA. If you resend the data,
        any action the form carried out (such as a saerch or online purchase) 
        will be repeated. To resend the data, click OK. Otherwise, click Cancel.   
      
    (how many users understand this message?)

HttpServletResponse

  • Standard output is sent directly back to the client browser
  • Represent the HTTP response a web application sends back to the browser, in response to the HTTP request the browser sends to the web application.
  • To send response back to the browser
    • The Content-Type header (i.e., a response header) that tells the browser the type of the content to be sending back must be specified.
      • text/html -- send html back to the browser
      • text/plain -- send plain text back to the browser
    • A PrintWriter from the HttpServletResponse object must be obtained and use print() and println() to write HTML to browser
    • Example html from name.html
               
          <html>
            <head>
               <title>Name</title>
            </head>
      
            <body>
              <form method="post" action="http://cs.gmu.edu:8080/offutt/servlet/name">
                  Please enter your name:
                  <input type="text" name="yourname" value="your name">
                  <br />
                  <input type="submit" value="Submit" name="submit">
                  <input type="reset" value="Reset" name="reset">
              </form> 
            </body> 
          </html>
        
      Example servlet from name.java
                
          //Import Servlet Libraries
          import javax.servlet.*;
          import javax.servlet.http.*;
      
          //Import Java Libraries
          import java.io.*;
          import java.util.*;
          import java.lang.*;
      
          public class name extends HttpServlet
          {
             public void doPost (HttpServletRequest req, HttpServletResponse res)
                         throws ServletException, IOException
             {
                res.setContentType ("text/html");
                PrintWriter out = res.getWriter ();
                          
                out.print ("<html>\n");
                out.print ("   <head>\n");
                out.print ("      <title>SWE 432: Name reading and printing</title>\n");
                out.print ("   </head>\n");
                out.print ("   <body>\n");
                out.print ("      <center><h2>Name reading and printing</h2></center>\n");
                out.print ("      <hr />\n");
      
                String Nm = req.getParameter("yourname"); 
                out.print ("      Your name is: <font color=green>");
                out.print (Nm);
                out.print ("      </font>\n");
                out.print ("   </body>\n");
                out.print ("</html>\n");
      
                out.close ();
             }
           }
        

Redirecting to another URL from servlets

Servlets usually generate an HTML ile as a response, but sometimes you might want to send the client to a different servlet.
    res.sendRedirect (“http://apps-swe432.vse.gmu.edu:8080/ ...”);
  
  • The client will be sent to the specified URL
  • Server tells the client to generate another request to the new URL
  • Browser then repeats the request to the new URL
  • Control is transfered to a new URL and does not come back

Writing to file from servlets

  • File must be in a publicly writeable directory
    /data/apps-swe43/swe432/WEB-INF/data/
  • Open a file
    FileWriter outfile = new FileWriter("/data/apps-swe432/swe432/WEB-INF/data/info-file.txt");
    Open a file in append mode
    FileWriter outfile = new FileWriter("/data/apps-swe432/swe432/WEB-INF/data/info-file.txt", true);
  • Write to a file
    outfile.write( .... data to save .... );
  • Close a file
    outfile.close();
  • Remember that we all share the same directory ... include your user name as part of the file name

HTTP requests

GET requests

  • Generated when the URL is entered directly or when method="GET" is used in an HTML form
  • doGet() is called from service()
  • The length of GET parameters is limited by some browsers (usually 1024 bytes)
  • Put form data on the URL as parameters
    http://www.example.com/servlet/PrintThis?arg=Hello&color=red&age=39
  • Use GET when no data is sent (or just to receive data from server)

POST requests

  • Generated when method="POST" is used in an HTML form
  • The length can be arbitrarily
  • Put form data in body of request
  • Use POST when sending data to server
    • To change state on server (update file or database)
    • When there are a lot of data items

Deployment Testing

  • Development and deployment computers often differ
  • Web apps must be tested on final deployment platform
    • Must test just as real users use it
  • Issues to check for
    • Different platforms (DOS / Unix / Linux / Mac ...)
      • File names and path names (local/nonlocal, DOS/Unix)
      • Upper case dependencies
    • Incomplete deployment
    • Compiler and runtime system version
    • Permissions (data and DB)