Servlet Container A web server uses a separate module to load and runservlets. Such specialized module dedicated to the servletmanagement, is called a servlet container, or servletengine. Browser sends requests to the web server. If the targetis an HTML file, the server handles it directly. If thetarget is a servlet, the server delegates the request tothe servlet container, which in turn forwards it to theservlet. A servlet container is a part of the web server, eventhough it may run in a separate process.
Types of Servlet Containers Standalone: These are Java-based web servers where thetwo modules—the main web server and the servletcontainer are integral parts of a single program. In-process: The main web server and the servlet containerare different programs, but the container runs within theaddress space of the main server as a plug-in. Out-of-process: Like in-process servers, the main webserver and the servlet container are different programs, butthe web server runs in one process while the servletcontainer runs in a separate process. To communicate with the servlet container, the web serveruses a plug-in, which is usually provided by the servletcontainer vendor.
The javax.servlet package The package contains the generic servlet interfaces andclasses that are independent of any protocol. The javax.servlet.Servlet interface: It is a centralinterface in the Servlet API. Every servlet class mustdirectly or indirectly implement this interface. The javax.servlet.GenericServlet class: It is an abstractclass that provides implementation for all the methodsexcept the service() method (which is abstract) of theServlet interface. The javax.servlet.ServletRequest interface: It provides ageneric view of the request that was sent by a client anddefines methods that extract information from the request. The javax.servlet.ServletResponse interface: It providesa generic way of sending responses and defines methodsthat assist in sending a proper response to the client.
Methods of the Servlet interface init(): It is called by the servlet container to indicate to theservlet that it must initialize itself and get ready for service. Thecontainer passes an object of type ServletConfig as a parameter. service(): It is called by the servlet container for each requestfrom the client to allow the servlet to respond to the request. destroy(): It is called by the servlet container to indicate to theservlet that it must clean up itself, release any acquired resource,and get ready to go out of service. getServletConfig(): It returns information about the servlet,such as a parameter to the init() method. getServletInfo(): The implementation class must returninformation about the servlet, such as the author, the version,and copyright information.
The javax.servlet.http package The package provides basic functionality required for HTTPservlets. All Interfaces and classes extend the correspondinginterfaces and classes of the javax.servlet package to support theHTTP protocol. The javax.servlet.http.HttpServlet class: It is an abstract classthat extends GenericServlet and adds a new service() method. The javax.servlet.http.HttpServletRequest interface: Itextends ServletRequest and provides an HTTP-specific view ofthe request by providing methods that extract information suchas HTTP headers and cookies, from the request. The javax.servlet.http.HttpServletResponse interface: Itextends ServletResponse and provides an HTTP-specific way ofsending responses by defining methods that assist in settinginformation, such as HTTP headers and cookies, into theresponse.
The HTTP Protocol The Hypertext Transfer Protocol is a request-response-basedstateless protocol. A client opens a connection to the server and sends an HTTPrequest message. The client receives an HTTP response messagesent by the server and closes the connection. Once the server sends the response it forgets about the client. Uniform Resource Identifier: A URI is a string that identifiesany resource. Identifying the resource may not necessarily meanthat we can retrieve it. URI is a superset of URL and URN. Uniform Resource Locator: URIs that specify common Internetprotocols such as HTTP, FTP, and mailto are also called URLs. Uniform Resource Name: A URN is an identifier that uniquelyidentifies a resource but does not specify how to access theresource.
Parts of HTTP Message Initial line: Specifies the purpose of the request orresponse message Header section: Specifies meta-information, such as size,type, and encoding, about content of message. A Blank line An optional message body: The main content of therequest or response message. All the lines end with CRLF. The HTTP request has three parts, separated by spaces: • A method name. • The local path of the requested resource (URI). • The version of HTTP being used.
HTTP Request Method Names GET: It is used to retrieve a resource. If parameters are required,they are passed by appending a query string to the URI. The partafter the question mark is called a query string and consists ofparameter namevalue pairs separated by an ampersand (&). Maxlimit 255 characters. Data is part of URL, only text, cached inBrowser history and target resource type is Active or Passive. HEAD: It is used to retrieve the meta-information about aresource. The response for a HEAD request contains only theheader. POST: It is used to send data to the server in order to beprocessed i.e. post the data to the active resource identified bythis URI. Characters can be unlimited. Data is not part of URL,both text and binary, not cached in Browser history and targetresource type is Active. PUT: It is used to add a resource to the server. It puts the datasent in the message body and associate it with the given Request-URI.
Methods in HttpServlet CLass For every HTTP method, there is a corresponding method in theHttpServlet class of type: public void doXXX(HttpServletRequest, HttpServletResponse)throws ServletException, IOException;where doXXX() depends on the HTTP method.HTTP Method HttpServlet MethodGET doGet()HEAD doHead()POST doPost()PUT doPut()DELETE doDelete()OPTIONS doOptions()TRACE doTrace()
Handling HTTP Requests The servlet container calls the service(ServletRequest,ServletResponse) method of HttpServlet. The service(ServletRequest, ServletResponse) method ofHttp-Servlet calls the overloadedservice(HttpServletRequest, HttpServlet-Response)method of the same class. The service(HttpServletRequest, HttpServletResponse)method of HttpServlet analyzes the request and finds outwhich HTTP method is being used. Depending on theHTTP method, it calls the corresponding doXXX() methodof the servlet. The Servlet API specifies the interfaces and the servletcontainer provides the classes that implement theseinterfaces.
ServletRequest Methods ServletRequest is to retrieve the parameters sent by aclient. String getParameter(String paramName): Itreturns just one of the values associated with the givenparameter. String getParameterValues(String paramName):It returns all the values associated with the parameter. Enumeration getParameterNames(): It is usefulwhen you don’t know the names of the parameters.You can iterate through the Enumeration of Stringsreturned by this method and for each element you cancall getParameter() or getParameterValues().
HttpServletRequest Methods String getHeader(String headerName): This methodreturns just one of the values associated with the givenheader. Enumeration getHeaderValues(String headerName):This method returns all the values associated with theheader as an Enumeration of String object. Enumeration getHeaderNames(): This method is usefulwhen you don’t know the names of the headers. One caniterate through the enumeration returned by this method,and for each element you can call getHeader() orgetHeaderValues().
HttpServletResponse Methods void setHeader(String name, String value): Used to set the name-value pair for a header in the ServletRequest. void setIntHeader(String name, int value): Converts the int value tostring. void setDateHeader(String name, long millisecs): Same as above. void addHeader / addIntHeader / addDateHeader: Associatesmultiple values with the same header. boolean containsHeader(String name): Returns a Boolean that tellswhether or not a header with this name is already set. Typical response header names Date: Specifies the current time at the server. Expires: Specifies the time when the content can be considered stale. Last-Modified: Specifies the time when the document was lastmodified. Refresh: Tells the browser to reload the page
HttpServletResponse Methods sendRedirect(String url): redirects the browser toanother resource. The call to this method throws throw ajava.lang.IllegalStateException if the response is committedi.e. if the response header has already been sent to thebrowser. The sendRedirect() method is not transparent to thebrowser and, the servlet sends a message telling thebrowser to get the resource from the given URL. sendError(int status_code , String message): HTTPdefines status codes for common error conditions in theHttpServletResponse interface as constants. The sendErrormethod send status to the client and displays anappropriate message.
Servlet Life CycleLoadedUnloadedDestroyedInitialized Servicingstartupshutdownshutdownservice()service()init()destroy()
Loading and Instantiating a Servlet On start up of a servlet container, it looks for a set ofconfig files, called deployment descriptors, describingall the web applications. The deployment descriptor includes an entry for eachof the servlets, were an entry specifies the name of theservlet and a Java class name for the servlet. The servlet container creates an instance of the givenservlet class using the methodClass.forName(className).newInstance() loading theservlet. The servlet class generally has no constructor.
Initializing a Servlet The servlet container calls the init(ServletConfig) methodon the newly created instance. The ServletConfig object contains all the initializationparameters that are specified in the deployment descriptorof the web application. The servlet container calls the init() method once and onlyonce on a servlet instance. The servlet specification defines the <load-on-startup>element, which can be specified in the deploymentdescriptor to make the servlet container load and initializethe servlet as soon as it starts up. Such process of loading aservlet before any request comes in is called preloading, orpreinitializing, a servlet.
Servicing Client Requests Once the servlet instance is initialized, it is ready toservice client requests. When the servlet container receives requests for theservlet, it dispatches them to the servlet instance bycalling theServlet.service(ServletRequest, ServletResponse)method
Destroying and Unloading a Servlet Destroying a Servlet: If the servlet container decides that it no longer needs a servletinstance, it calls the destroy() method on the servlet instance. Once destroyed, the servlet instance is out of service and the containernever calls the service() method on that instance. The servlet container cannot reuse the instance in any way and theservlet instance may only go to the unloaded state from current state. Before calling the destroy() method, the servlet container waits for theremaining threads, executing the servlet’s service() method to finish. A servlet container may destroy a servlet if it is running low onresources and no request has arrived for a servlet in a long time. A servlet container may also destroy a servlet if it is shutting down. Unloading a Servlet: Once destroyed, the servlet instance may be garbage collected, inwhich case the servlet instance is said to be unloaded. If the servlet has been destroyed because the servlet container isshutting down, the servlet class is also unloaded.
ServletConfig The ServletConfig interface is defined in the javax.servletpackage and has methods for retrieving initialization parametersas follows: String getInitParameter(String name): It returns the value ofthe parameter or null if no such parameter is available. Enumeration getInitParameterNames(): It returns anEnumeration of Strings for all the parameter names. ServletContext getServletContext(): It returns theServletContext for the servlet. String getServletName(): It returns the servlet name asspecified in the configuration file. ServletConfig provides methods only to retrieve parameters andone cannot add or set parameters to the ServletConfig object A servlet container gets the information specified about a servletin the deployment descriptor and wraps it into a ServletConfigobject which is retrieved by the servlet during initialization.
ServletContext ServletContext interface is like a window for a servlet to view itsenvironment. A servlet uses the interface to get information, such asinitialization parameters for the web application or retrievingshared resources or for logging. Every web application has one and only one ServletContext, andit is accessible to all the active resources of that application. It is also used by the servlets to share data with one another. Methods of ServletContext to access any resource are as follows: java.net.URL getResource(String path): It returns ajava.net.URL object for the resource that is mapped to the givenpath. Although the path should start with / it is not an absolutepath. It is relative to the document root of this web application. java.io.InputStream getResourceAsStream(String path): Itis a shortcut method to get an InputStream out of the resource. Itis equivalent to getResource(path).openStream(). String getRealPath(String relativePath): It converts a relativepath to an absolute path.
Sharing Data and Attribute Scope The ServletRequest, HttpSession, and ServletContextobjects provide a setAttribute(String name, Objectvalue) method to add the name-value pair in the containerand an Object getAttribute(String name) method toreturn the value mapped to the given name. Objects shared using ServletRequest are accessible only forthe life of a request. Objects shared using HttpSession are accessible only whilethe client is active. Objects shared using ServletContext are accessible for thelife of the web application. Enumeration getAttributeNames(): The method returnsan Enumeration of Strings for all names that are availablein the container.
RequestDispatcher Interface void forward(ServletRequest request, ServletResponse response): Itallows a servlet to process a request partially and then forwards the request toanother servlet for generating the final response. It can forward a request fromone active resource (servlet or JSP page) to another resource (servlet, JSP orHTML page) on the server. It can be called only if the response is notcommitted; else, it throws an IllegalStateException. void include(ServletRequest request, ServletResponse response): Similarto forward(), but the request is not “forwarded” permanently. Instead, it ispassed to the other resource temporarily so that the other resource can partiallyprocess the request, and then the forwarding servlet/JSP page can take over therequest again and service it to completion. Because the request is notforwarded permanently, all changes to the headers or status code of the requestmade by the other resource are ignored. The difference between forward() and sendRedirect() is that forward() iscompletely handled on the server side while sendRedirect() sends a redirectmessage to the browser. Hence forward() is transparent to the browser whilesendRedirect() is not.
RequestDispatcher RequestDispatcher can be accessed using both ServletContextand ServletRequest objects. RequestDispatcher getRequestDispatcher(String path):Return RequestDispatcher object were the path parameter is thepath to the resource which should not be a path outside thecurrent web application. The ServletContext interface provides agetNamedDispatcher() method, allowing to dispatch requeststo a component by specifying its name (as given in thedeployment descriptor) instead of a full URI path. One can pass a relative path to the getRequestDispatcher()method of ServletRequest but not to the getRequestDispatcher()method of ServletContext. ServletRequest evaluates the path relative to the path of thecurrent request, while ServletContext has no current requestpath hence the path parameter cannot be relative and must startwith /.
Web Container Directory Structure The webapps directory under Tomcat installation isthe home directory of all web applications that ithosts. All publicly accessible files should go in this directory. Every web application must have a WEB-INFdirectory directly under its root directory. Files in the WEB-INF directory are not served to theclients.
WEB-INF Directory Structure classes directory: The servlet class files and the class filesneeded to support the servlets or JSP pages of the webapplication go in classes directory if they are not been includedin a JAR file. The class files should be organized according totheir packages which are added as directories at runtime by theservlet container to the classpath for the web application. lib directory: All the JAR/zip files used by the web application,including the third-party JAR/zip files, go in this directory. Forexample, if a servlet uses JDBC to connect to a database, theJDBC driver JAR file should go here. We can also package theservlet classes in a JAR file and keep that file in this directory. Atruntime, the servlet container adds all the JAR/zip files from thisdirectory to the classpath for this web application. web.xml file: A deployment descriptor file is the heart of a webapplication, and every web application must have it. It containsthe information needed by the servlet container in order to runthe web application, such as servlet declarations and mappings,properties, authorization and security constraints, and so forth.
The Servlet Element Each <servlet> element under <web-app> defines aservlet for that web application. <servlet> <servlet-name>ServletName</servlet-name> <servlet-class>ServletClass</servlet-class> <init-param> // servlet parameter <param-name>parametername</param-name> <param-value>parametervalue</param-value> </init-param> </servlet>
The <servlet> element servlet-name: It defines the name for the servlet. Such name isused to access the servlet and define servlet mapping. Thiselement is mandatory, and the name should be unique across thedeployment descriptor. servlet-class: It specifies the Java class name that should beused by the servlet container to instantiate the servlet. Thiselement is mandatory and the class, as well as all the classes thatit depends on, should be available in the classpath for this webapplication. The classes directory and JAR files in lib directoryinside WEB-INF are automatically added to classpath by theservlet container. init-param: The element is used to pass initializationparameters to the servlet. There can be any number of <init-param> elements in the <servlet> element. Each <initparam>element must have one and only one set of <param-name> and<paramvalue> subelements. <param-name> defines the name ofthe parameter and must be unique across the servlet element.<param-value> defines the value for that parameter.
The <servlet-mapping> element The servlet container uses the servlet mappings to invoke theappropriate servlet depending on the actual URL pattern. <servlet-mapping> <servlet-name>servletname</servlet-name> <url-pattern>/account/*</url-pattern> </servlet-mapping> A string beginning with a / and ending with /* characters is usedfor determining a servlet path mapping. A string beginning with a *. prefix is used to map the request to aservlet that handles the extension specified in the string. All other strings are used as exact matches only. A string containing only the / character indicates that servletspecified by the mapping becomes the default servlet of theapplication.
Mapping a URL to a servlet Routing a request to a servlet is a two-step process. The servlet container first identifies the web application thatbelongs to the request, and then it finds an appropriate servlet ofthat web application to handle the request. The request URI into three parts: the context path, the servletpath, and the path info were: Request URI = context path + servlet path + path info. Context paths and servlet paths start with a / but do not endwith it. HttpServletRequest provides three methods—getContextPath(), getServletPath() and getPathInfo()in order to retrieve thecontext path, the servlet path, and the path info, respectively,associated with a request.
Context path, Servlet path, Pathinfo Context path: The servlet container tries to match thelongest possible part of the request URI, starting from thebeginning, with the available web application names. Thispart is called the context path. If there is no match, thecontext path is empty; in such case, it associates therequest with the default web application. Servlet path: After taking out the context path, the servletcontainer tries to match the longest possible part of theremaining URI with the servlet mappings defined for theweb application specified as the context path. This part iscalled the servlet path. If unable to find any match, itreturns an error page. Path info: Anything that remains after determining theservlet path is called path info.
ServletContext Initialization Every web application has exactly one instance ofjavax.servlet.ServletContext initialized at the time ofloading of the web application. The initialization parameters for a servlet are defined in thedeployment descriptor of the web application. The servlets of a web application can retrieve theseinitialization parameters using the methods of theServletContext interface as follows: String getInitParameter(String name): It returns aString containing the value of the parameter, or null if theparameter does not exist. java.util.Enumeration getInitParameterNames(): Itreturns an Enumeration of the names of the context’sinitialization parameters.
Listener Interfaces The Servlet Specification 2.3 defines listener interfaces as away to receive notifications when important events occur. The listener interface provides methods which are called byservlet container when the corresponding events occur.The interfaces are as follows: ServletContextListener and ServletContextEvent ServletContextAttributeListener andServletContextAttributeEvent HttpSessionAttributeListener andHttpSessionBindingEvent All three listener interfaces extend java.util.EventListener.
ServletContextListener & ServletContextAttributeListener The ServletContextListener interface provides methods used tonotify when ServletContext is initialized or destroyed. void contextDestroyed(ServletContextEvent sce): Called when thecontext is destroyed. void contextInitialized(ServletContextEvent sce): Called when thecontext is initialized. The ServletContextAttributeListener interface is used to receivenotifications about the changes to the attribute list of a servlet context.Methods are: void attributeAdded(ServletContextAttributeEvent scae): called whena new attribute is added to the servlet context. void attributeRemoved(ServletContextAttributeEvent scae): calledwhen an existing attribute is removed from the servlet context. void attributeReplaced(ServletContextAttributeEvent scae): calledwhen an attribute of the servlet context is replaced. The ServletContextEvent extends java.util.EventObject and theServletContextAttributeEvent class extends the ServletContextEventclass.
HttpSessionAttributeListener The HttpSessionAttributeListener interface allows a developer toreceive notifications whenever changes occur to the attribute list of theHttpSession object. These changes include adding a new attribute, removing an existingattribute, and replacing an existing attribute. void attributeAdded(HttpSessionBindingEvent se): It is calledwhen an attribute is added to a session. void attributeRemoved(HttpSessionBindingEvent se): It is calledwhen an attribute is removed from a session. void attributeReplaced(HttpSessionBindingEvent se): It is calledwhen an attribute is replaced in a session. In order to receive notifications we specify the class that implementsthe interface in the deployment descriptor in order to receive thenotifications. The HttpSessionBindingEvent class extends from the HttpSessionEventclass and provides the name and value of the attribute that is added toor removed or replaced from the session
Properties of Web Application The properties of the web application are accessible through ServletContextand apply to all of the components of a web application: display-name: Defines a short name that can be used by development tools,such as IDEs. description: Defines the usage and any important information for to thedeployer. distributable: Indicates that the application can be distributed across multipleJVMs. context-param: Specifies initialization parameters for the web application. Itcontains a <param-name>, a <param-value>, and an optional <description>element. An application can have as many <context-param> elements asneeded. listener: It specifies the classes that listen for the application events. Itcontains one and only one listener-class element which specifies the fullyqualified class name of the class that implements the listener interface. Theevent for which the class is used is not specified, but the servlet containerfigures it out. The container delivers the events to the listeners in the order theclasses are specified in the deployment descriptor.
Error Handling Methods void sendError(int sc): Sends the status code to the client andclears the response buffer. void sendError(int sc, String msg): Sends the status code aswell as the message to the client and clears the response buffer. Both methods throw a java.lang.IllegalStateException if theresponse is already committed. HttpServletResponse also provides a setStatus() method: void setStatus(int sc): Sets the status code for the response. The setStatus method does not trigger the container to generatean error page. It just sends the status code to the browser, whichis displayed by the browser as per its settings.
Declarative Exception Handling The servlet container uses the mapping from the deploymentdescriptor to map the exception with a servlet, in order to displayproper error pages in response to exceptions. The error-page element specifies such mapping defines as: <!ELEMENT error-page ((error-code | exception-type),location)> The error-page is associated with an exception type or an errorcode with a resource. Each <error-page> element describes one mapping: • error-code: Specifies the HTTP error code (such as 404) for anerror-page mapping and must be unique across all the error-pagemappings. • exception-type: Specifies the full exception class name for anerror-page mapping and must be unique across all the error-pagemappings. • location: Specifies the resource for an error-page mapping. Thevalue must start with a /.
Declarative Exception Handling In the doXXX() methods of the Servlet interface cannot throwany exception other than ServletException and IOException, orthe RuntimeException or their subclasses. All other exceptions are wrapped in ServletException, andrethrown as ServletException. The wrapped exception is calledthe root exception, or root cause. The container uses ServletException.getRootCause() methodto extract the wrapped exception and tries to find a match for itin deployment descriptor. Custom exceptions can be thrown by extending the customexceptions from RuntimeException, ServletException, orIOException. If the status code of the response is set then before sending theresponse to the browser, the servlet container looks through allthe <error-page> elements and tries to find an error page whichis mapped to the status code. If the container finds an error page,it will use that page to generate a response; otherwise, it willsend a default error page.
Attributes of Error Handler The servlet container sets certain attributes in the request beforedispatching it to the error page to help error handler servlet (JSP)page to analyze the problem and generate a detailed response. The attributes for Error Handler in javax.servlet.error packageare as follows: status_code (Integer): Contains the status_code value passed inthe setStatus() or sendError() methods. exception_type (Class): Contains the Class object for theuncaught exception. message (String): Contains the message passed in thesendError() method or the message contained in the uncaughtexception. exception (Throwable): Contains the uncaught exception thatinvokes the error page request_uri (String): The current request URI. servlet_name (String): Contains the name of the servlet thatcaused the error page to be invoked
Handling exceptions of RequestDispatcher If the servlet forwarded or included by RequestDispatcherthrows an exception the include() or forward() ends withan exception. If the exception thrown by the included or forwardedresource is a RuntimeException, a ServletException, or anIOException, it is thrown as is by the include() or forward()method. Otherwise, the exception is wrapped in a ServletExceptionas the rootCause, and the ServletException is thrown bythe include() or forward() method. The calling servlet gets a chance to handle the exceptionsgenerated by the included or forwarded resource
Logging The logging methods provided by both GenericServlet andServletContext are as follows: void log(java.lang.String msg): Writes the given messageto the log file void log(java.lang.String message,java.lang.Throwable t): Writes the given message and astack trace for the given Throwable object to the log file. The actual file used to log the messages depends on theservlet container. The GenericServlet log methods prepend the servlet nameto the message while the ServletContext methods do not.
HttpSession The methods of HttpServletRequest interface: HttpSession getSession(boolean create): This methodreturns the current HttpSession associated with this request, orif there is no current session and the create parameter is true,then it returns a new session. If create parameters is false, thenreturns null. HttpSession getSession(): This method is equivalent to callinggetSession(true). Methods of HttpSession interface: void setAttribute(String name, Object value): This methodadds the passed object to the session, using the name specified. Object getAttribute(String name): This method returns theobject bound with the specified name in this session, or null ifno object is bound under the name.
Session Event Listener Interfaces The javax.servlet.http package defines four listeners andtwo events: HttpSessionAttributeListener andHttpSessionBindingEvent: Notifications on changes onattribute list of HttpSession objects. HttpSessionBindingListener andHttpSessionBindingEvent: Implemented by objects toreceive notifications when they are added or removed fromsession. No need to inform the container about such objectsexplicitly. Its methods are as follows: void valueBound(HttpSessionBindingEvent event):Notifies the object that it is being bound to a session. void valueUnbound(HttpSessionBindingEvent event):Notifies the object that it is being unbound from a session.
Session Event Listener Interfaces The servlet container calls the interface methods even if thesession is explicitly invalidated or has timed out. HttpSessionAttributeListener is configured in the deploymentdescriptor and the container creates only one instance of thespecified class. HttpSessionBindingEvents is not configured in deploymentdescriptor and generated from all sessions, are sent to object &called when the object is added/removed from session. HttpSessionAttributeListener interface is used to track theactivity of all the sessions. HttpSessionBindingListener interface is used to take actionswhen certain kinds of objects are added to or removed from asession.
Session Event Listener Interfaces HttpSessionListener and HttpSessionEvent: TheHttpSessionListener interface is used to receive notifications when asession is created or destroyed. The listener class implementing this interface must be configured inthe deployment descriptor. void sessionCreated(HttpSessionEvent se): This method is calledwhen a session is created. void sessionDestroyed(HttpSessionEvent se): This method is calledwhen a session is destroyed HttpSessionActivationListener and HttpSessionEvent: It is used bythe session attributes to receive notifications when a session is beingmigrated across the JVMs in a distributed environment. The methodsare as follows: void sessionDidActivate(HttpSessionEvent se): This method iscalled just after the session is activated. void sessionWillPassivate(HttpSessionEvent se): This method iscalled when the session is about to be passivated. All four listener interfaces extend java.util.EventListener. HttpSessionEvent extends java.util.EventObject andHttpSessionBindingEvent extends HttpSessionEvent.
Session Termination Method to invalidate session programmatically. void invalidate(): This method invalidates thesession and then unbinds any objects bound to it. The valueUnbound() method will be called on all of itsattributes that implementHttpSessionBindingListener. It throws an IllegalStateException if the session isalready invalidated.
Session Timeout If a user does not perform any action for a certain period of time, theserver invalidates the session. The configuration of the timeout period of a session. <session-config> <session-timeout>30</session-timeout> </session-config> The <session-timeout> element contains the timeout in minutes. Avalue of 0 or less means that the session will never expire. HttpSession Methods to get and set the timeout values are as follows: void setMaxInactiveInterval(int seconds): This method specifiesthe number of seconds between client requests before the servletcontainer will invalidate this session. A negative value means that thesession will never expire. int getMaxInactiveInterval(): This method returns the maximumtime interval, in seconds, that the servlet container will keep thissession open between client accesses. It affects only the session onwhich it is called.
Session Creation Process A new client sends a request to a server without session ID. The server creates a session and assigns it a new session ID. The server uses the session.isNew() to determine if thesession is in new state or not. The server then sends the ID back to the client with theresponse. The client gets the session ID and saves it for futurerequests, making him aware of the session on server. The client sends another request with the session ID. The server receives the request, observes the session ID andassociates the request with the session created earlier. Atthis time, the client joins the session and the session is nolonger in the new state. Therefore, a call to session.isNew()will return false.
Session using Cookies The servlet container uses HTTP headers to managesessions. While sending a response, a servlet container adds aspecial header line containing the session ID. The client (browser), receives the response, extracts thespecial header line, and stores it on the local machine ascookie. While sending another request, the client automaticallyadds a header line containing the stored session ID. A header line is just a name-value pair. The header name used for sending a cookie is cookie. If the cookies are disabled, the cookie header lines areignored by the browser and session cannot be managedusing cookies.
Session using URL Rewriting In absence of cookie support, the session ID is attached to all ofthe URLs within an HTML page sent as a response to the client. Hence on clicking the URL, the session ID is automatically sentback to the server as part of request line. Unlike cookies, URL rewriting is not transparent to the user. Methods for encoding URL in HttpServletResponse. String encodeURL(String url): It returns the URL with thesession ID attached and used for normal URLs emitted by aservlet. String encodeRedirectURL(String url): It returns the URLwith the session ID attached. It is used for encoding a URL thatis to be used for the HttpServletResponse.sendRedirect()method. Both methods first check to see if attaching the session ID isnecessary.
Sessions using URL Rewriting If request has cookie header line, i.e. cookies are enabled, thenthere is no URL rewriting. JSESSIONID is appended to the URL using a ; and part of thepath info of the request URI and is not a request parameter. URL rewriting is a very robust way to support sessions. It is used when cookie support is uncertain. All the URLs should be encoded, including all the hyperlinksand action attributes of the forms, in all the pages of theapplication. All the pages of the application should be dynamic as there is noway to attach session IDs to the URLs in HTML pages. All the static HTML pages must run through a servlet, to rewritethe URLs while sending the pages to the client. URL Rewriting hence involves a serious performance bottleneck.
HTTP Authentication Mechanisms HTTP Basic authentication: The server sends theWWW-Authenticate header specifying authentication typeand the realm (context of valid authentication). Browsersends username and unencrypted password. HTTP Digestauthentication: Same as Basic Authentication but thepassword is encrypted. HTTPS Client authentication: It is HTTP over SSL. Allthe data is transmitted in the encrypted form using public-key cryptography handled by browser and servletcontainer. Requires certificate from CA and is costly. HTTP FORM-based authentication: Similar to Basicauthentication, but instead of browser dialog box anHTML FORM to capture the username and password. Theaction attribute of the form is j_security_check and hastwo fields: j_username and j_password.
Specifying Authentication Mechanism The authentication mechanism is specified in thedeployment descriptor using the <login-config>. <auth-method>: Specifies which of the fourauthentication methods should be used to validate theuser: BASIC, DIGEST, CLIENT-CERT, or FORM. • <realm-name>: Specifies the realm name to be usedin HTTP Basic authorization only. • <form-login-config>: Specifies the login page URLand the error page URL. This element is used only ifauth-method is FORM; otherwise, it is ignored.
Declarative Security It is specifying the detailed security requirements of the webapplication in the deployment descriptor. It involves follows: Web resource collection: Identifies the resources of theapplication i.e., HTML files, servlets, etc that must be protectedfrom public access. A user must have appropriate authorizationto access resources identified under a web resource collection. Authorization constraint: Identifies the roles that a user canbe assigned. Instead of specifying permissions for individualusers, permissions are assigned to roles. User data constraint: Specifies the mechanism of datatransmission between the sender and the receiver i.e. thetransport layer requirement of the application in order tomaintain data integrity and confidentiality. All the above contraints are configured in the deploymentdescriptor by using the element <security-constraint>.
<security-constraint> element display-name: It specifies a name for the security constraint. web-resource-collection: It specifies a collection of resourcesto which the security constraint applies. Multiple web resourceconstraints can also be defined. Defination is as follows: <!ELEMENT web-resource-collection (web-resource-name,description?, url-pattern*, http-method*)> web-resource-name: Specifies the name of the resource. description: Provides a description of the resource. url-pattern: Specifies the URL pattern through which theresource will be accessed. Multiple URL patterns can be specifiedto group multiple resources together. Also used to specify theURL-to-servlet mapping. http-method: It specifies the HTTP methods to which thisconstraint will be applied. The methods specified in <http-method> have a restricted access while all other requests to theseservlets will be open to all users. If no <http-method> element is present, then the constraintapplies to all of the HTTP methods.
<security-constraint> element auth-constraint: It specifies the roles that can accessthe resources specified in the webresource-collectionsection. <!ELEMENT auth-constraint (description?, role-name*)> description: Describes the constraint. role-name: Specifies the role that can access theresources. It can be * (all roles), or a name defined inthe <security-role> element of the deploymentdescriptor.
<security-constraint> element user-data-constraint: It specifies how the data should becommunicated between the client and the server. <!ELEMENT user-data-constraint (description?, transport-guarantee)> description: Describes the constraint. transport-guarantee: Contains one of three values: NONE,INTEGRAL, or CONFIDENTIAL. NONE implies that the application does not need any guaranteeabout the integrity or confidentiality of the data transmitted. INTEGRAL and CONFIDENTIAL imply that the applicationrequires the data transmission to have data integrity andconfidentiality, respectively. Plain HTTP is used when transport-guarantee is set to NONE,and HTTPS is used when transport-guarantee is set toINTEGRAL or CONFIDENTIAL.
Programmatic Security In Programmatic Security, the servlet identifies the role which auser plays and then generates the output according to the role. HttpServletRequest interface provides three methods foridentifying the user and the role. String getRemoteUser(): This method returns the login nameof the user, if the user has been authenticated, or null if the userhas not been authenticated. Principal getUserPrincipal(): This method returns ajava.security.Principal object containing the name of the currentauthenticated user. It returns null if user is not authenticated. boolean isUserInRole(String rolename): This methodreturns a Boolean indicating whether the authenticated user isincluded in the specified logical role. It returns false if the user isnot authenticated. The <security-role-ref> section is used to associate one rolename used by the servlet to the other role name in deploymentdescriptor.
MultiThreaded Servlet Model The container maintains a thread pool to service requests. A thread pool is a set of worker threads waiting to executethe given code. A servlet container also has a thread called the dispatcherthread that manages the worker threads. When the container receives a request for a servlet, thedispatcher thread picks up a worker thread from the pooland dispatches the request to the worker thread which thenexecutes the service() method. The servlet container does not bother if the second requestis for the same servlet or another servlet. It picks up newthread in the pool if current thread is still working. When the container receives multiple requests for oneservlet simultaneously, the service() method of that servletwill be executed concurrently in multiple threads.
Single Threaded Model It is used by the servlets that cannot perform the tasks inparallel. The SingleThreadModel interface in the javax.servletpackage is implemented by the servlet which cannotservice requests concurrently. The servlet container may create multiple instances of theservlet class to process multiple requests simultaneously. The creation of multiple instances consumes time as wellas memory and does not alleviate from multithreadingissues. Instance variables cannot be shared among multiplerequest. Synchronizing service() method of a servlet instead ofimplementing the SingleThreadModel interface is a goodsolution to make the servlet thread safe.
Variable Scope and Thread Safety Local variables: Each thread gets its own copy of the localvariables, and hence are always thread safe. They cannot be used to share data between threads. Instance variables: There is only one copy of the instancevariables per instance of the servlet, and all of the threadsshare this copy. In the case of the multithreaded model, multiple threadsmay access an instance variable simultaneously, making itunsafe. In the case of the single-threaded model, only one threadexecutes the methods of a servlet instance at a time, henceis thread safe. Instance variables can be used throughout the life of theservlet.
Variable Scope and Thread Safety Class (or static) variables: Only one copy of a class variable exists across all theinstances of the object belonging to the class for whichit is declared. Class variables are not thread safe. Class variables are unsafe for the singlethreadedmodel, because multiple threads may access the sameclass variable from different servlet instances. Class variables are used to store read only or constantdata.
Attribute Scope and Thread Safety Context scope: It is accessible to all the servlets of a webapplication. Multiple threads can set and get attributes simultaneously fromthe servlet context, making the data stored in it inconsistent. Context scope is used to share data that is seldom modified. Session scope: HttpSession is accessible only to the threads thatare servicing requests belonging to that session. It is not threadsafe and the HttpSession object must besynchronized to enable thread safety to make it thread safe. Request scope: ServletRequest object is accessed by only onethread as the servlet container creates a new ServletRequestobject for each request that it receives. The request scope object is thread safe as only one threadservices the request. The ServletRequest object is passed as a parameter to theservice() method and is valid only for the scope of the service()method of the servlet. It is used when a request is to beforwarded to another resource.