0
0
0
6,966

Servlets 3.0 Tutorial

jorge.simao
Posted 3/28/14

Servlets 3.0 Tutorial Java WebApp at the Core

Abstract

Servlets Tutorial on Servlets 3.0 API, with presentation of concepts, explanation of the API, examples, and links to related frameworks supporting a more high-level programming model.

Introducing Servlets

Servlets are Java classes that can be used as web application components on the server side. Servlets are part of a set of JEE technologies that are used to develop web applications on the server side. The Servlet standard that defines the API available to applications and a set of requirements that servlet containers must comply with.

This tutorial gives a detailed overview of Servlet technology, including: understanding the role of Servlet in Java based web application, how to write Servlets classes, how to use the Servlet API in abstract and practical context.

These days Servlets are less popular as technology at the application level. Java web frameworks using MVC architecture(s) are mostly used to develop applications. However, virtually all of this Java frameworks rely on Servlets as a front-end to the application services and components. Thus, understanding Servlet technology continues to be relevant for application programmers. Deep knowledge of Servlet technology is also essential to all Java middleware programmers working on frameworks for web development.

Technologically, Servlets sit in the same niche as CGI for C programs, and PHP scripts. There are however reasons to claim that Java Servlet is superior to other technologies. PHP is very popular for "home-grown" and "mid-sized" projects, but in the context of enterprise applications Java is more popular and arguably a more suitable technology specially when it comes to performance and standartization.

The Servlet API

Servlets are Java classes that handle network requests from a client and provide some response as output. Although the Servlet specification allow for Servlet to be used with arbitrary network protocols, in practice Servlet are mostly used with the HTTP protocol.

The Servlet standard API is defined by the interface javax.servlet.Servlet. The key method defined in this interface is Servlet.service() that is invoked by servlet container so that client requests are handled and a response is produced. A generic Servlet implementation is provided in class GenericServlet. Application may extend this class to handle arbitrary networking protocols.

Additionally, the servlet API defines class javax.servlet.http.HttpServlet (that extends GenericServlet ) to handle HTTP requests and responses. Application servlets working in a web environment should extends this class.

The Servlet Interface

The javax.servlet.Servlet interface defines the core methods of the servlet API. These methods can be roughly grouped in two categories: methods to manage the servlet life-cycle and request handling; and methods that allow the Servlet to access information about its operating enviroment.

Below, we show the specification of the Servlet interface.
interface Servlet {
 void init(ServletConfig config);
 void destroy();
 void service(ServletRequest request, ServletResponse response);

 ServletConfig getServletConfig();
 String getServletInfo();
}

Method init() and destroy() are used for life-time management. An instance of type ServletConfig is passed to the init() method. This allow the Servlet instance of learn about its configuration and container environment. Method getServletConfig() is another way get this information. Implementation of Servlet should save the ServletConfig passed to init() to be able to provide it on call to getServletConfig(). The class GenericServlet does that.

Method getServletInfo() is used to get description string about the servlet.

Method service() it used to handle requests. This is a fairly low-level method and its independent of protocol details. It has two parameters. The first parameter ServletRequest encapsulates the client request. The second parameter ServletResponse encapsulates the response, including a stream where the response data can be written.

HTTP Servlets

For the specific case of HTTP protocol the class HttpServlet is provided. This class provides an implementation of method service() suitable to handle HTTP request. Since HTTP has a limited number of request methods, the method HttpServlet.service() maps each of the HTTP methods to a different class method. Thus, HTTP method GET is mapped to java method doGet , POST to doPost , and so on.

Below, we show the definition of the HttpServlet class with a few of the methods used to map HTTP methods:

abstract class HttpServlet extends GenericServlet {
	void doGet();
//handle HTTP GET requests
	void doPost();
//handle HTTP POST requests	
	void doPut();
//handle HTTP PUT requests
	void doDelete();
//handle HTTP DELETE requests
	...
}

An implementation of an HttpServlet will override some sub-set of the HTTP handling methods, according to the need to the application. For a web application the method doGet() is typically overriden to handle HTTP GET methods (e.g. from a browser). Below, we show the skeleton for such as servlet:

public class MyWebServlet extends HttpServlet {

	void doGet(HttpServletRequest rqst, HttpServletResponse rsp)
		throws ServletException, IOException {

		...

	}
}

Servlet Architectures

A single Java web application can have one or several HTTP servlets. Each servlet should map to a different part of URL namespace. Each servlet can inspect HTTP headers and parameters to decide how to handle the request. Different servlet is typically responsible for different services or produce different web views.

One special case is a (complex) application that is implemented with a single servlet. In this case, this servlet should look at request information, such as URL suffix, to select further processing and selection of web view. This is the approach often used by MVC web frameworks.

The output produced by a Servlet can be static or dynamic generated content. HTML is the common format for output views in web application. In implementing web services XML-based domain data, and non-XML domain data, or even binary data, are also possible and common.

Servlet Life Cycle

A Servlet container is (a part of) an application server that manages a set of servlets. The container listen for TCP/IP connections, understand the HTTP protocol, and creates and invokes servlets as needed.

The life cycle of a Servlet is controlled by the servlet container where it is deployed. Methods in the servlet are invoked to let the Servlet to know about lifecyle events and perform appropriate actions. The following steps are performed by the servlet container:

  1. On receiving a request, the container maps the request URL to decide which servlet should handle the request.
  2. If an instance of the mapped Servlet class is not being managed by the container, then it performs the following steps:
    1. Loads the servlet class;
    2. Creates an instance of the servlet class;
    3. Initializes the servlet instance by calling the method init().
  3. To process each request, the method service() is invoked, creating and passing a request and response object.
  4. If the container needs to remove the servlet, it finalizes the servlet by calling method destroy().

Servlet Initialization

After a Servlet class is loaded and an instance is created, but before any client request is delivered, the servlet container invokes the Servlet to notify that initialization should take place. This gives oportunity to the Servlet to perform a variety of one-time tasks such as initialize resource specific to the Servlet implementatoin, get references to shared resources, and load persistent data.

Servlet initialization is done by invoking method init() on the application Servlet. Servlets should override this method to perform custom behavior. If an fatal error occurs during initialization, the servlet should thown a UnavailableException exception (derived form ServletException). This will provided feedataSourceack to the container that the initializatio was unsuccessful.

An example servlet with custom initialization is shown below as class MyServlet:

public class MyServlet extends HttpServlet {
	private DataSource dataSource;
	private Connection connection;
	
	public void init() throws ServletException {
		dataSource = (DataSource) getServletContext().getAttribute("datasource");
		if (dataSource == null) {
			throw new UnavailableException("MyServlet initalization error");
		}
		try {
			connection = dataSource.getConnection();
		} catch (SQLException ex) {
			throw new UnavailableException("Unable to get connection");					
		}		
	}
	...
}

The class MyServlet is a servlet for a web application, so it conviniently extends the class HttpServlet. The init method looks for a application scoped attribute named datasource for the value of the DataSource that is going to be used by the Servlet to perform SQL queries to some database driver. The actual initialization of the DataSource would typically occur in a Listener object.

If a connection is not found an UnavailableException is thrown. Otherwise, a connection is started for the datasource. If an error occurs while getting a connection an exception is also throw. Because SQLException is a checked exception and does not derive ServletException , an UnavailableException should be thrown.

Finalizing a Servlet

When a servlet container determines that a servlet should be removed from service it calls the destroy() method declared in the Servlet interface. Conditions for this to happen include:

  • The application is undeployed or showdown (by the user taking the role of manager of the servlet container and application server);
  • The container is low on resources and wants to reclaim used memory.

In the of implementation Servlet.destroy() , the Servlet should release any resources in use and perform final persistancy operations (e.g. database connections).

All of a servlet's service methods should be complete when a servlet is removed. The container tries to ensure this by calling the destroy() method only when all requests have been processed. The container may also ask finalization if a timeout as elapsed and some requests have not completed yet.

The example below show MyServlet with a destroy() method that close a connection to the database.

public class MyServlet extends HttpServlet {
	...
	public void destroy() {
		//release resources
		try {
			connection.close();
		} catch (SQLException ex) {
 	}
}

Servlet Deployment

Servlets are configured as part of a Java web application that is deployed in a standalone servlet container (e.g. Tomcat) or an application server. An XML file designated as the application descriptor file , named and located as /WEB-INF/web.xml , specifies the configuration for the application. Included in the web.xml file is the configuration of all servlet to be deployed.

Below, we show an example of a web.xml file that declares a single servlet of type myapp.web.MyServlet:

<?xml version="1.0" encoding="utf8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
	version="2.5">

<servlet>
	<servlet-name>myServlet</servlet-name>
	<servlet-class>myapp.web.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>myServlet</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

The XML namespace http://java.sun.com/xml/ns/j2ee is where the XML elements of the web.xml are defined. The top-level element is web-app where the namespace identifier and schema location are specified.

XML element <servlet> define an individual servlet. The sub-element <servlet-name> is used to give a name to the servlet that is used to reference it in other part of the configuration file. The sub-element <servlet-class> specifies the fully qualified name of the class of the Servlet.

The element servlet-mapping is used to define a URL prefix that maps to the servlet. The sub-element servlet-name reference the servlet. Sub-element <url-pattern> specifies the URL prefix. In the example above, we map myServlet to the root of the application. Thus, if the application is deployed with name myapp then any URL that has the prefix below maps to the servlet (assuming localhost on port 8080):

http://localhost:8080/mypp

Servlet Initialization Parameters

Servlet can be configured with some initialization parameters, as follows:
<web-app...
>

<servlet>
	<servlet-name>myServlet</servlet-name>
	<servlet-class>myapp.web.MyServlet</servlet-class>
	<init-param>
		<param-name>configLocation</param-name>
		<param-value>myServlet-config.xml </param-value>
	</init-param>
</servlet>
...
</web-app>

The XML element <init-param> is used to declare a servlet parameter. The sub-elements <param-name> specify the name of the parameter, and <param-value> a value for the parameters. This values are constants, as they can only be read but not modified by the servlet. In the example above, we set a parameter named configLocation with value myServlet-config.xml.

Application Initialization Parameters

In addition to Servlet specific initialization parameters, is also possible to setup global application parameters. This is done with XML element <context-param> as show below:

<web-app ... >

	<context-param>
		<param-name>myAppConfigLocation</param-name>
		 <param-value>myapp-config.xml</param-value>
	</context-param>
	...
</web-app>

Servlet Context

Servlets can have access to their configuration and the context where they are operating. This information includes configuration parameter, details about the servlet container, application scoped attributes, and so forth. The types ServletConfig and ServletContext are used store this information.

Getting the Servlet Configuration

A ServletConfig object is obtained by calling Servlet.getServletConfig()). Table below summarizes the methods of the ServletConfig interface.

MethodDescription
ServletContext getServletContext()getter for ServletContext
String getInitParameter(String name)Get init parameter
Enumeration getInitParameterNames()Get name of all init parameters
String getServletName()Get name of the servlet
API of ServletConfig.

Method getInitParameter() is used to get the value of a named intialization parameter for the Servlet. This correspond to parameters that where setup in the /WEB-INF/web.xml with XML element <init-param>. getInitParameterNames() gives an enumeration of all parameters names.

The code below show how a java.util.Map from Servlet parameters names to values can be build:

import java.util.Map;
import java.util.HashMap;
...

class ServletUtil {
	static Map<String, String> getParameters(ServletConfig config) {
		Enumeration<String> names = config.getInitParameterNames();
		Map<String, String> paramsMap = new HashMap<String, String>();
		while (params.hasMoreElements()) {
			String name = e.nextElement();
			paramsMap.put(name, config.getInitParameter(name));
		}
		return paramsMap;
	}
}

The Servlet Context

The ServletContext is the type that allow a Servlet to learn about its operating context. The ServletContext for a Servlet can be obtained by invoking ServletConfig.getServletContext() , or by invoking the utility method GenericServlet.getServletContext().

The information and services provided by a ServletContext object include: global initiatization parameters, management of application scoped attributes and values, access to resources availabe for the web application, and logging services. Table summarizes the API of the ServletContext. (Attribute related methods not shown.)

MethodDescription
ServletContext getContext(String uri)Get ServletContext for URL
String getServletContextName()Get application name (from web.xml)
String getInitParameter(String name)Get value of context-wide init parameter
Enumeration getInitParameterNames()Get all parameter names
RequestDispatcher getNamedDispatcher(String name)Get RequestDispatcher for named servlet
RequestDispatcher getRequestDispatcher(String path)Get RequestDispatcher for resource
String getRealPath(String path)Get real path from virtual path
URL getResource(String path)Get URL of resource from path
InputStream getResourceAsStream(String path)Get resource InputStream from path
Set getResourcePaths(String path)Get application resources matching path
String getMimeType(String file)Get MIME type of the specified file
void log(String msg)Log message to servlet log file
void log(String msg, Throwable throwable)Log message for Throwable
String getServerInfo()Get name/version of Servlet container
int getMajorVersion()Get major version of Java Servlet API
int getMinorVersion()Get minor version of Java Servlet API
API of ServletContext.

Scoped Objects

Web application are made of several types of components: servlets, beans, JSP pages, and embedded resources. Thus it is useful to have a mechanism to share information between the different components of the application. One way to do this is use scoped objects --- this are objects that have a life-time and availabitiry bound to a certain execution context designated the scope. Table below summarizes the set of scope objects available to servlets.

Scope ObjectClassAvailablity
Web contextjavax.servlet.ServletContextapplication servlets and beans
sessionjavax.servlet.http.HttpSessionrequests for the session
requestjavax.servlet.ServletRequestrequest handling servlet and beans
pagejavax.servlet.jsp.PageContextJSP page that creates the object
Scope Objects.

For each scoped object, an application may define attribute-value pairs to hold application relevant information. To store a new attribute and value, or replace a previous value, use methods setAttribute(String attr, Object value). To get the attribute value use methods Object getAttribute(String attr). Table below summarizes the methods of scoped objects to manage attributes. Note that the different scoped objects are not related by common interface or super-class, thus the methods are redefined and reimplemented for each scoped object.

ServletRequest MethodDescription
Object getAttribute(String name)Get attribute value
void setAttribute(String name, Object val)Set attribute value
void removeAttribute(String name)Remove attribute
Enumeration getAttributeNames()Get enumeration with all attibute names
API of ServletRequest and HttpServletRequest.

Request Handling

Servlets handle network requests to provide web-based distributed services to remote clients. The entry point for request handling is the service() method define in the Servlet interface. Application servlets override this method to implement the provided web service. For HTTP based services, the class HttpServlet implements the service() by dispatching to do*() methods, with each method corresponding to an HTTP method as defined in the standart specification(s). This includes: doGet() , doPost() , doPut() , doDelete() , doOptions() , doTrace(). This are the service methods invoked accroding to the HTTP method of the request send by a client.

Service handling methods are passed two argument: a request object implementing interface ServletRequest , and a response object of implementing interface ServletResponse. Forthe HTTP protocol, the HttpServlet invokes the HTTP specific service methods with a request objects of type HttpServletRequest and a response object of type HttpServletResponse. This HTTP specific interfaces extends the generic interfaces ServletRequest and ServletResponse , respectively.

The general pattern to implement a service method is to extract information from a request object, and send a response by writing to the output stream for the response. For HTTP servlets, the response include HTTP response headers and a response body. Mechanisms also exist to insert resources such as JSP pages in the response stream. Below, we outline the structure of a request handling method:

public class UserServlet extends HttpServlet {

	public void init() throws ServletException { ... }

	void doGet(HttpServletRequest rqst, HttpServletResponse rsp)
		throws ServletException, IOException {
		
		ServletContext context = getServletContext();

		//get request info and decide what to do (dispatching)
		//process request based on request and context info
			//write status code
			//write HTTP header
			//get output stream
			//write HTTP body
			//and/or include resources
			 ...
		//close output stream
	
}

Getting Information from Requests

Request objects provide a variety of method to get information about the request send the client and the session that that the request is part. Basic information about the request is accessed by invoking methods in the ServletRequest. This includes, the identity of the client that sent the request, its preferred options for the response (such as locale), information about the protocol used to send the request, and the communication endpoint of the server.

It is also possible to retrieve an input stream for the request and manually parse the data. To read binary data, the method getInputStream() provides a ServletInputStream object. To read character data, the method getReader() provides a BufferedReader object.

A ServletRequest is also a scoped object thus is provides attribute storage and management services. This allow sharing of information between the components involved in handling each request. Table below summarizes the API of the ServletRequest. (Attribute management and parameter access methods not shown.)

The derived interface HtmlServletRequest provides additional HTTP specific information. Including: URL of request, content of the HTTP headers, and the request body. This is discussed in more detail the following sections.

ServletRequest MethodDescription
ServletInputStream getInputStream()Get binary stream for request body
BufferedReader getReader()Get char stream for request body
String getCharacterEncoding()Get char enconding of request
void setCharacterEncoding(String enc)Override char enconding
int getContentLength()Get length in bytes of the request body
String getContentType()Get MIME type of the body of the request
Locale getLocale()Get preferred Locale for the client
Enumeration getLocales()Get all locales (starting with preferred)
String getProtocol()Get protocol/major.minor Version (e.g. HTTP/1.1)
boolean isSecure()Check if a secure channel was used (e.g. HTTPS)
String getScheme()Get protocolo scheme for request (e.g. http, https, ftp)
String getRemoteAddr()Get IP address of client host
String getRemoteHost()Get DNS name of client host
String getServerName()Get hostname of the server
int getServerPort()Get server port
RequestDispatcherGet resource handler
getRequestDispatcher(String path)
API of ServletRequest.

URL Path Elements

An HTTP request always contains a URL to uniquely identify the resource that client wants to access. The URL contains several pieces of information put together in a string, including: the protocol and endpoint information that allowed the networking infrastructure to send the request to servlet container; the request path made of the prefix that is mapped to a specific servlet and the remaining resource identifier handled by the servlet; and a query string. Below, we show the general structure of an URL:

URL ::= {proto}://{host}:{port}/{contextPath}/{servletPath}/pathInfo?{query}
proto ::= http|https
The Servlet API distinguishes and provided accesses to several sub-segments of the request path:
Context path
The prefix for the deployed application.
Servlet path
The prefix that mapped to servlet handling the request.
Path info
The remaining segment of the request path adter the context path or the servlet path.

All returned path segments starts with a forward slash '/'.

Table below shown some examples of parsing URLs into sub-segments.
Request PathContextServletInfo
/myapp/myservlet/users/list.html/myapp/myservletusers/list.html
/abc-store/user-chart/123/abc-store/user-char 123
Examples of parsing a URL's request path into sub-segments.
Each of the sub-segment of a path may be get by invoking a method of HttpServletRequest. Table below summarizes these methods. The method String getMethod() is also include in the table. It is used to return the HTTP method specified by the client together with the request URL.
HttpServletRequest MethodDescription
StringBuffer getRequestURL()Get request URL
String getRequestURI()Get request URL (excluding query string)
String getContextPath()Get URI segment for context
String getServletPath()Get segment of URL for servelet
String getPathTranslated()Get URL segment after servlet name and before query string
String getPathInfo()Get extra URL segement
String getQueryString()Get query string segment of URL
String getMethod()Get HTTP method of the request
Methods of HttpServletRequest related to access request URL.

Query Strings and Request Parameters

Query strings are set of parameter--values pairs, used to submit information from the client to the server. They may be generated by in one of two ways: by explicitly specifying in a link to a URL that contains a query string; or, more usually, it is added to a URL automatically by a browser in responde to a HTML FORM submittion. Each of the named input fields of a FORM will produce a parameter value in the query string. A {query} has the following format:
param1=value1,param2=value2,...

To extracts a parameter value from a request use method getParameter(). It returns the string value of the query parameter or null if not defined. An example is show below:

 void doGet(HttpServletRequest rqst, HttpServletResponse rsp)
	throws ServletException, IOException {
	
	String val = rqst.getParameter("paramName");
	if (val != null) {
	 if (!val.isEmpty() {
	...
	 </h3>
	}
}

Table below summarizes the methods of HttpServletRequest used to access request parameters.

ServletRequest MethodDescription
String getParameter(String name)Get query parameter
Map getParameterMap()Get map with all query parameters
Enumeration getParameterNames()Get all query parameter names
String[] getParameterValues(String name)Get all values of a parameter
Method of ServletRequest to get query parameters and values.

Getting HTTP Headers

HTTP request headers are processed and consumed by a HttpServlet before the service methods are invoked. Thus request streams returned by getInputStream() and getReader() only allow reading of the body of the request. To get the identity of the HTTP headers of the request and to read its content, additional methods are provided by HttpServlet. Table below summarizes these methods.

HttpServletRequest MethodDescription
String getHeader(String name)Get request header
Enumeration getHeaderNames()Get all header names
Enumeration getHeaders(String name)Get all values for header
int getIntHeader(String name)Get header value as int
long getDateHeader(String name)Get value of header as a Date
Method of HttpServletRequest API to access HTTP headers.

Constructing Responses

The ServletResponse interface provides the methods a servlet required to send a response to a client. This includes the the output stream to write te response to, response options (such as the text encoding and content type), and management of output buffer.

For a HttpServlet , the HttpServletResponse provides method specific to the HTTP protocolos, including: setting of HTTP headers, and sending of HTTP response status.

Response Streams and Body

The method getOutputStream() of a ServletResponse object is used to get the binary response stream for the response of type ServletOutputStream. Method getWriter() is used to get text response stream of type PrintWriter. Application servlets should write to one of these stream objects to send content to the client. It also possible to used both streams (e.g. to send a multipart response, with text data interleaved with binary data). The typicall code pattern is shown below:

 void doGet(HttpServletRequest rqst, HttpServletResponse rsp);
 ...
	
	PrintWriter out = rpst.getWriter();

	//write the response
	out.println(...);

	out.close();
}
...
}

Method setContentType() is used to set MIME type of the response (e.g. text/html). A registry of content type names is kept by the Internet Assigned Numbers Authority (IANA) at:

ftp://ftp.isi.edu/in-notes/iana/assignments/media-types

Methods setLocale() and getLocale() are used to set and get the locale to use for the response. This are only configuration option, no output is inserted in the response by setting the locale. Servlet methods and collaborating components handling the request should get the locale information and invoke objects that recognize and adapt to the locale.

Table below summarizes the the method of the HttpServletResponse API to get response streams and configure response options.
MethodDescription
ServletOutputStream getOutputStream()Get binary response stream
PrintWriter getWriter()Get text response stream
boolean isCommitted()Check if response has been committed
void setContentLength(int len)Sets length of body in HTTP Content-Length header
void setContentType(String type)Set MIME type of response body
String getCharacterEncoding()Get char encoding for MIME body
Locale getLocale()Get locale for the response
void setLocale(Locale loc)Set locale for response (including charset in Content-Type header)
void addCookie(Cookie cookie)Add cookie to response
String encodeRedirectURL(String url)Encode URL for use in sendRedirect method
String encodeURL(String url)Encode URL by including the session ID in it
API of ServletResponse and HtmlServletResponse.

Setting HTTP Headers

HTTP response objects, HttpServletResponse, have fields representing HTTP headers such as: * Status codes, which are used to indicate the reason a request is not satisfied. * Cookies, which are used to store application-specific information at the client. Sometimes cookies are used to maintain an identifier for tracking a user's session (see Maintaining Client State).
 public void doGet (HttpServletRequest rqs, HttpServletResponse rps)
	throws ServletException, IOException {
	
	//write HTTP headers before body
	rps.setContentType("text/html");
	rps.setBufferSize(8192);
Table below summarizes the methods of the HttpServletResponse API for setting HTTP headers.
MethodDescription
void addHeader(String name, String value)Add header with a value
void setHeader(String name, String value)Set value of header
void addIntHeader(String name, int value)Add header with interger value
void setIntHeader(String name, int value)Sent value of integer header
void addDateHeader(String name, long date)Add date header
void setDateHeader(String name, long date)Set value of Date header
boolean containsHeader(String name)Check if named header has been set
Methods of HtmlServletResponse for HTTP headers.

Redirection and HTTP Status

Table below summarizes the methods of the HttpServletResponse API for setting HTTP headers.
MethodDescription
void sendRedirect(String loc)Send temporary redirect to client
void sendError(int sc)Send HTTP status/response to client
void sendError(int sc, String msg)Send HTTP status/response to client with message
void setStatus(int sc)Set status code of response
Methods of HtmlServletResponse API for HTTP redirection and status codes.

Buffer Management

Indicate whether to buffer output. By default, any content written to the output stream is immediately sent to the client. Buffering allows content to be written before anything is actually sent back to the client, thus providing the servlet with more time to set appropriate status codes and headers or forward to another Web resource.

Table below summarizes tthe method of the ServletResponse API for buffer management.
MethodDescription
void flushBuffer()Forces response buffer to be sent to client
int getBufferSize()Get actual buffer size for response
void setBufferSize(int size)Sets preferred buffer size for response
void reset()Clears response data, status code and headers
void resetBuffer()Clears reponse data
Method of ServletResponse API for buffer management.

Web Resources

Including Resources

Including Other Resources in the Response

	RequestDispatcher rd = getServletContext().getRequestDispatcher("/banner");
	if (rd != null) rd.include(rqs, rps);

Redirecting

Transferring Control to Another Web Page.

Sessions

Many web application required that information about a user interaction be shared across multiple requests. The collective of requests and shared information for a individual user is called a session. Since HTTP protocol is by design state-less, its the responsability of web applications to store and manage session information in some way. The Servlet API provides support for session management. For HTTP a session object is represented by interface HttpSession.

To get access to a session object use method getSession() of the request object. This method returns the current session associated with this request, or, if none exists, it create a new session object. Since method getSession() may modify the response header (if cookies are the session tracking mechanism), it needs to be called before getting the output stream from the response. Table below summarizes the sub-set of the API of HttpSession interface related to sessions.

MethodDescription
HttpSession getSession()Get session of the request (create if needed)
HttpSession getSession(boolean create)Get session of the request (create if none and requested)
String getRequestedSessionId()Get session ID specified by client
boolean isRequestedSessionIdFromCookie()Check if session ID came from a cookie
boolean isRequestedSessionIdFromURL()Check if session ID came for URL
boolean isRequestedSessionIdValid()Check is session ID is still valid
Cookie[] getCookies()Get array of Cookies for this request
Methods of the HttpServletRequest API to access information about sessions.

Session API

Table below summarizes the API of the HttpSession interface. (Attribute management methods not shown.)

MethodDescription
String getId()Get unique session ID
long getCreationTime()Get time of session creation (ms since 1-1-70 0:00GMT)
boolean isNew()Check if client know about session
long getLastAccessedTime()Get time of last request
int getMaxInactiveInterval()Get max time the container will keep the session
void setMaxInactiveInterval(int sec)Set max time container will keep the session
void invalidate()Invalid session
ServletContext getServletContext()Get ServletContext
API of HttpSession interface.

Session Attributes

A session is conversational context between a client browser and a server. Conversational state can be saved as session scoped attributes, which can be created, set, and looked up as the application needs. The type HttpSession defines the API to managed the session and and the session scoped attributes.

HttpSession session = rqst.getSession();
ShoppingCart cart = (ShoppingCart)session.getAttribute("shoppingCard");
List<OrderItem> = cart.getItems();
...

Session Management

Each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed with a session's [get|set]MaxInactiveInterval methods. You can also set the timeout period in deploytool: When a particular client interaction is finished, you use the session's invalidate method to invalidate a session on the server side and remove any session data.

Session Tracking

A Web container can use several methods to associate a session with a user, all of which involve passing an identifier between the client and server. The identifier can be maintained on the client as a cookie or the Web component can include the identifier in every URL that is returned to the client.

If your application makes use of session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response's encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.

Event Listeners

It is possible to learn about application and servlet live-cycle events, by using event listeners objects. This is useful because application may use multiple servlet, and thus event handling is more naturally done in separated classes. An application of listerner is when some resources are shared among servlets. Thus, its better design to implement creation, initialization and release of shared resources with a listener. Some resource also need to be create and/or access at relevant points such as when a new session is created or a session is closed. Event listeners provide this to be done naturally.

Two types of objects can be listened for events: the ServletContext and HttpSession. For this two types events are triggered: to notify that the object has been initialized or are about to be destroyed; and when attributed have been added, removed, or replaced from this objects. Different listeners interfaces and event objects are used for the different object and live-cycle events. When a event is triggered listerner registered are invoked using the method and event object to provide information about the event. Table below summaries the interfaces, event types, and notification method defined in package javax.servlet.*.

ObjectListenerEvent ClassMethod
Web contextServletContextListenerServletContextEventcontextInitialized
contextDestroyed
Web contextServletContextAttributeListenerServletContextAttributeEventattributeAdded
attributeRemoved()
attributeReplaced()
Servlet Listeners and Events.

Event Handling

import javax.servlet.*;
import java.sql.*;
import javax.sql.*;
import org.apache.derby.jdbc.*;

public final class ContextListener implements ServletContextListener {
	public void contextInitialized(ServletContextEvent ev) {
		ServletContext context = ev.getServletContext();
		try {
			DataSource dataSource = new DataSource();
			context.setAttribute("datasource", dataSource);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		Integer hits = new Integer(0);
		context.setAttribute("hits", hits);
		//context.log("Created hitCounter" + counter.getCounter());
	}

	public void contextDestroyed(ServletContextEvent event) {
		ServletContext context = event.getServletContext();
		DataSource dataSource = context.getAttribute("datasource");
		dataSource.close();
		context.removeAttribute("datasource");
		context.removeAttribute("hits");
	}
 
	private DataSource createDataSource() { 
		ClientDataSource datasource = new org.apache.derby.jdbc.ClientDataSource();
		datasource.setServerName("localhost");
		datasource.setPortNumber(12345);
		datasource.setDatabaseName("mydb");
	}
}

Registering Listeners

Filters

A filter is an object that can transform the header or content or both of a request or response. Filters differ from Web components in that they usually do not themselves create a response. Instead, a filter provides functionality that can be "attached" to any kind of Web resource. As a consequence, a filter should not have any dependencies on a Web resource for which it is acting as a filter, so that it can be composable with more than one type of Web resource. The main tasks that a filter can perform are as follows:

  • Query the request and act accordingly.
  • Block the request-and-response pair from passing any further.
  • Modify the request headers and data. You do this by providing a customized version of the request.
  • Modify the response headers and data. You do this by providing a customized version of the response.
  • Interact with external resources.

Applications of filters include security (authentication and access control), access logging, image conversion, data compression, encryption, and XML transformations with stylesheets.

You can configure a Web resource to be filtered by a chain of zero, one, or more filters in a specific order. This chain is specified when the Web application containing the component is deployed and is instantiated when a Web container loads the component. For each web resource a filter chain will be operating.

Programming Filters

The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. The most important method in this interface is the doFilter method, which is passed request, response, and filter chain objects.

In the doFilter method, both filters retrieve the servlet context from the filter configuration object so that they can access the counters stored as context attributes. After the filters have completed application-specific processing, they invoke doFilter on the filter chain object passed into the original doFilter method. The elided code is discussed in the next section.

public final class MyFilter implements Filter {
	private FilterConfig filterContext;

	public void init(FilterConfig filterContext) throws ServletException {
		this.filterContext = filterContext;
	}

	public void doFilter(ServletRequest rqst,
		ServletResponse rsp, FilterChain chain) 
		throws ServletException, IOException {
	 
		if (filterContext == null) {
			return;
		}
	
		ServletContext context = filterContext.getServletContext();
		
		Integer hits = (Integer)context.getAttribute("hits");
		hits.inc();
	 
		context.log("#hits:" + hits);
	 
		chain.doFilter(rqst, rsp);
	}
}

Installing Filters

Filter Mappings

Security

Table below summarizes the methods of the HttpServletRequest API related to security.

HttpServletRequest Method Description
String getRemoteUser() Get identify of autdenticated user
String getAuthType() Get name of authentication scheme
Principal getUserPrincipal() Get Principal object for authenticated user
boolean isUserInRole(String role) Check if user has role
Methods of HttpServletRequest related to security.

MVC Architecture

Custom Front Controller


No Comments

Post First Comment

Login (or Register)
Contribute Feedback