Servlets


A servlet is a Java class that extends the HttpServlet (javax.servlet. http.HttpServlet) class and implements the Servlet (javax.servlet.Servlet) interface.

Servlets execute in the context of a J2EE Web container handling HTTP requests and providing dynamically generated responses. For this reason, servlets are used to provide dynamic Web content and flow control for Web applications. They are also used as front-ends to session beans, as XML processors for B2B applications and as Web server applications for non-EJB environments.

Tip

Servlets, although able to return dynamic HTML pages, are better used in conjunction with JSPs. In this scenario, servlets prepare business data and store information in Java beans. They then forward the request to a JSP, which generates HTML for the client.


Servlets have access to J2EE services such as JDBC, JNDI, JTA, and JMS. However, unlike the EJB container, they do not support declarative features for transactions, security, and persistence.

Servlets have a number of features for managing client requests and serving dynamic Web content. These features and more are discussed in the following sections.

Servlet Session Management

A Web or HTTP session is a series of related requests from a client to a particular Web site within a given time period. Sessions allow clients to traverse multiple Web pages and retain contextual information across these pages.

A session begins when a client first contacts a Web site. During a session, clients use a number of Web pages. A session can end for a number of reasons, for example:

  • A user exits the Web client.

  • The session times out due to inactivity.

    Note

    Web containers support inactivity timeouts for a session.


  • The Session is invalidated on the server side. For example, a session can be invalidated when a client logs out of the site with site-specific login/logout pages.

Servlet Context Information

Servlets are created by the Web container and participate in sessions with Web clients. Each session consists of a series of HTTP requests and responses. Servlets can store and access contextual information regarding their session through the following objects and methods :

  • HTTPSession object is used to store information for a session. The methods getAttribute and setAttribute are used to retrieve and store data specific to a session.

  • HttpServlet is a base class for servlets and it implements the ServletConfig interface. Servlets define initialization parameters in the vendor-independent web.xml deployment descriptor. These values are read using the getInitParameter method of this object.

  • ServletContext is stored in the HttpServlet object. This class has the getAttribute and setAttribute methods, which are used for retrieving and storing data specific to a servlet object.

  • An object implementing the HTTPServletRequest interface is created and passed as an argument to the doGet or doPost methods of a servlet by the Web container. This HTTPServletRequest object contains contextual information for the current request; for example, the request URL, HTTP headers, and the query string.

  • HTTPResponse interface is used to return content to the client. In addition to the content to be rendered, the response can contain persistent information specific to a client; for example, cookies.

Caution

Because servlets are multithreaded, developers must be careful when using shared resources, such as the Web context and instance variables because inconsistencies can occur through concurrent access.


Servlet Lifecycle

Servlets are created by the Web container the first time a request is made for them. Upon the initial servlet request, the Web container loads the servlet class from storage, creates an instance of it, and invokes the init method of the HttpServlet object. The developer can override the init method and perform servlet-specific initialization.

After the servlet is created and initialized , it can handle HTTP requests and responses. An HTTP request generally is a GET or POST operation. A GET operation uses the query-string in the URL to transfer information. The POST operation uses the message body to transfer information and supports larger and more efficient data transfers. An object implementing the HTTServletRequest interface is passed as an argument to the doGet and doPost methods of the servlet. The developer overrides these methods to handle requests.

The HTTPServletRequest object contains cookie information, the query string data, and binary data in the message body. The servlet also uses this information to perform its work. When the request is processed , the servlet using the HTTPServletResponse object (also passed as a parameter to the doGet or doPost methods of a servlet) fills out the response header, setting cookie values if necessary. When this task is complete, the servlet either dynamically builds the content for the response or forwards the request to another servlet or JSP. The response is eventually returned to the requestor by the Web container.

When the servlet is no longer needed, for example if the servlet class changes on disk and must be reloaded, the Web container removes the servlet from memory after calling the destroy method of HttpServlet class.

Servlet Request Filtering

Servlets support chains of request filters. A filter is an object that transforms the header or body of an HTTP request or response. Hence Servlets, for example, can be used to customize requests and responses, authenticate requests, and transform XML data.

Servlet Dispatch Control

Servlets can dispatch requests to other servlets or to JSPs. The RequestDispatcher object has methods that allow the servlet to forward requests to and include content from other servlets and JSPs. The RequestDispatcher object is obtained from the ServletContext or HTTPServletRequest objects as discussed earlier.

Servlet Security

Servlets use the Web container's authentication mechanism. They can provide authorization by using the getUserPrincipal or isUserInRole methods in the HTTPServletRequest interface. Security roles and constraints are defined the web.xml deployment descriptor. However, the mechanism for mapping users to roles is performed by the Web container provider and hence is vendor-specific.

Servlets and Persistent Client Information (Cookies)

Cookies provide long- term user-specific information to be maintained on the client side. Cookies are a piece of information that the Web server asks the client browser to save locally on a user's disk. Each time a browser accesses the same Web server, it sends all the cookies belonging to that site as part of the HTTP request. Cookies are stored as a name , value pair.

Invoking Servlets Through URL Query Strings

The HttpServlet class provides most of the structure needed by a servlet. The application developer primarily has to be concerned with overriding the doGet and doPost methods. These methods handle the incoming HTTP request and prepare an HTTP response.

Servlets are activated by supplying a URL to the Web container using the following URL syntax:

 
 http://host:port/appName/servletPath?query-string 

where:

  • http://host:port identifies the Web container listening for incoming requests at a specific port.

    Note

    The http://host:port is also known as the document or context root for a Web server/container.


  • appName identifies the Web application name as defined in the web.xml deployment descriptor.

  • servletPath defines the location of the servlet class file relative to where the Web application is stored by the Web container.

  • query-string is request-specific information passed to the servlet.

Declaring and Configuring Servlets

All servlet declarations and configurations are performed via the vendor-neutral web.xml and vendor-specific deployment descriptor XML-based files respectively. Through these deployment descriptor files you can

  • Declare EJBs referenced by the servlet.

  • Declare resources, such as databases used by the servlet.

  • Define security roles and security constraints to restrict access to the servlet.

  • Map HTTP error codes to other Web components for standardizing error reporting.

  • Use filter mapping to associate a Filter class with a URL pattern or specific servlet.

  • Initialize servlet-level environment values.

For technical information on developing servlets in the context of WebLogic Server 7.0, see "Introduction to Servlets," p. 549 .




BEA WebLogic Platform 7
BEA WebLogic Platform 7
ISBN: 0789727129
EAN: 2147483647
Year: 2003
Pages: 360

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net