Working with Servlets

A servlet is a server-side component (Java class) that is deployed, executed, and managed by a J2EE-compliant Web container (Web server). A servlet handles HTTP requests and provides HTTP responses, usually in the form of an HTML, XML, or text document.

Servlets are most effectively used for implementing presentation logic and generating binary content such as images. A servlet in the Web tier allows a Web client (browser) to indirectly interact with EJB business logic.

Servlets are portable and non-transactional Java components, which run in servlet engine (container) that can run on any operating system or hardware. They are analogous to the applets that are used on the client container (Web browser). Servlets are the backbone of any e-commerce application such as online shopping carts, financial services, and personalized content. They are mainly used to get and validate user input, authenticate user identity, and generate dynamic Web content that responds to the user's input.

Servlets are used to track a user session in Web applications, such as shopping carts. They also can be used to access directory and naming services, databases, JMS messaging services, and JavaMail. They can be used to build secure applications by using Access Control Lists (ACLs) for authentication and Secure Sockets Layer (SSL) to provide encryption for secure communications. The most important use of servlets is to act as controllers and delegates in accessing EJBs to encapsulate sessions, data from databases, and other functionality.

The following few sections will give brief descriptions of the servlet API, accompanied with few examples. Later today, we'll demonstrate how servlets work as controllers and are used to access EJBs as client delegates.

Creating a Simple Servlet

Servlets are defined in the javax.servlet package. To write a servlet, you must extend the javax.servlet.http.HttpServlet class (which implements the javax.servlet.Servlet interface). The Web container instantiates the servlet by calling the init() method of the Servlet interface. All requests are dispatched by the container to the service() method, which is the heart of servlet operations. Based on the request type, the service() method dispatches calls to other specialized service methods. For example, the service() method dispatches HTTP GET requests to be handled by the service method doGet(), and HTTP POST requests to be handled by doPost() method, and so on. To implement a servlet, you must override any of the service methods. Each of the service methods runs on a separate thread of execution. Finally, the Web container removes the servlet from memory after calling the destroy() method. The following is the basic code to write a simple servlet:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimpleServlet extends HttpServlet {
  // The service method handles HTTP requests and response
  public void service(HttpServletRequest request,
                      HttpServletResponse response)
                      throws IOException, ServletException {
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.print("<html><head><title>" +
                 "Hello from my first Servlet!</title></head><body>" +
                 "<h3>Hello from my first Servlet!</h3></body></html>");
  }
  public void init(ServletConfig config)  throws ServletException{
      super.init(config);
  }
}

In the preceding example, the SimpleServlet extends the HttpServlet class and overrides only the generic service() method.

Note

If you choose to implement the service() method, you cannot implement the doPost() or doGet() method unless you call super.service() at the beginning of your service() method.


Any of the service methods accepts an HTTP request from the Web browser as input, and returns an HTTP response as output, as defined by the HttpServletRequest and HttpServletResponse classes, respectively.

Note

HTTP request types can be GET, POST, PUT, HEAD, DELETE, OPTIONS, or TRACE. The corresponding service methods are doGet(), doPost(), doPut(), and so on. Each doXXX() method accepts the same parameters as the service() method.


In the response parameter, you first set the content type to "text/html", get a reference to a java.io.PrintWriter object to use for output, and then create some HTML using the print() method of the PrintWriter object.

The init() method is called by the container before any service method. It accepts one parameter as an object of the ServletConfig class, which contains configuration data set by the Web container. The init() method must call the super.init() method. In some Web applications, the init() method is used to establish a connection to external resources, which can be cleaned up in the destroy() method before the servlet ends its life cycle.

Our SimpleServlet can then be compiled and deployed to a J2EE-compliant Web container. To run the servlet, you simply call it by its URI from your browser. Servlets and other resources (such as JSPs and images) are packaged into a single unit (or module) called a Web application. A Web application utilizes a specific directory structure to contain its resources and a deployment descriptor web.xml file that defines how these resources interact and how the Web application is accessed by a Web client. A Web application may also be deployed as an archive file called a .war file. Figure 7.2 illustrates the directory structure of a sample Web application.

Figure 7.2. Directory structure of a sample Web application.


The servlet API has one exception, ServletException, which can be thrown when the servlet encounters difficulty.

Note

By default, the servlet architecture is multithreaded, which generally boosts the application's scalability. However, you can set your servlets to work in a single-threaded model by implementing the SingleThreadModel interface.


Processing Client Requests

One of the major tasks of servlets is to process client requests to generate a result. Servlets use the HttpServletRequest method to retrieve data from the request object. Table 7.1 summarizes the methods of the HttpServletRequest.

Table 7.1. Summary of Methods of HttpServletRequest Class
MethodDescription
getMethod()Returns the name of the HTTP method; for example, GET, POST, or PUT.
getQueryString()Enables you to access the query string (the remainder of the requested URL, following the ? character) of the HTTP GET method.
getParameter(String name)Returns the value of a parameter as a String.
getParameterNames()Returns an array of all the parameter names.
getParameterValues()Returns an enumeration of values for all the parameter.
getInputStream()Retrieves the body of the request as binary data.

Here is an example to illustrate how to extract the request parameters and display them out on the screen. The following is the source of the FORM containing the login information of Figure 7.3:

<HTML>
<HEAD>
<TITLE>University Registration Page</TITLE>
</HEAD>
<BODY>
<FORM METHOD="POST" NAME="RegistrationPage"
           ACTION="/servlet/DisplayParameters">
<h3>Registration Form</h3>
 Login name<input type="text" size=20 name="loginname" value=""><br>
 Password : <input type="password" size=20 name="password" value="" ><br>
 First Name:<input type="text" size=20 name="firstname" value="" ><br>
 Last Name:<input type="text" size=20 name="lastname" value="" ><br>
 <input type="submit" value="Register" name="registerbutton"><br>
</FORM>
</BODY>
</HTML>

Figure 7.3. Logon form to the university registration system.


You'll notice that the preceding form uses the POST method and targets the DisplayParameters servlet, as displayed in the Action tag.

Note

There are two methods in submitting forms: POST and GET. The POST method sends the action and the parameters as name/value pairs in the body of the message. The GET method sends this data appended to the URL, which is exposed to the user. Use GET if the length of your value strings is not long (less than 8KB). POST is appropriate for long messages with more private information.


The following is the listing of the DisplayParameters servlet, which will display all the parameters of the form and their values on the screen:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class DisplayParameters extends HttpServlet{
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Enumeration params = request.getParameterNames();
    while(params.hasMoreElements()) {
      String param = (String)params.nextElement();
      out.println(param + " : ");
      String[] paramValues = request.getParameterValues(param);
      if (paramValues.length == 1)
          out.print(paramValues[0]);
      else
        for(int i=0; i< paramValues.length; i++)
          out.println(paramValues[i]);
    }
  }

When the preceding servlet is executed, the Web container directs the request to the service() method, which in turn dispatches it to the doPost() method.

Handling Both Static and Dynamic Content

Servlets generate both dynamic and static content to construct a Web page. When delivering content, a good practice is to cache all static content in the init() method, which reduces the creation time for every request. The following listing shows a technique you can use when you want to use servlets to deliver both static data and dynamic data to the client:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class CacheServlet extends HttpServlet{
  byte[] header, footer, navbar;
  byte[] staticContent;
  public void init(ServletConfig config) throws ServletException{
     super.init();
     // Cache all the static content
     StringBuffer tmp = new StringBuffer();
     // Cache the header
     tmp.append("<html><head><title>");
     tmp.append("University Registration</title></head><body>");
     header = tmp.toString().getBytes();
     // Cache the footer, and navbar here
  }
  public void service(HttpServletRequest req, HttpServletResponse res)
           throws ServletException, IOException {
     res.setContentType("text/html");
     PrintWriter out = res.getWriter();
     out.write(new String(header));
     out.write(new String(navbar));
     // write dynamic data here for the body
     out.write(new String(footer));
  }
}

This caching technique enhances your application performance because static data is ready to be delivered in the response. Figure 7.4 depicts a site wire-frame in which dynamic content is generated for the body part of the page outline.

Figure 7.4. Static and dynamic content generation.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.196.172