Monday, April 4, 2011

Chapter 30: Servlet API

In the previous sections, we saw in depth about the Servlet and what it can do as the back bone of a J2EE application. This chapter is a synopsis of whatever we learnt about the servlet and would help you revise for the exam.

So, lets get started!!!

Introduction to the Chapter:

This chapter describes the javax.servlet package, mostly taken from the content that is generated from the javadocs, which define the actual Java classes and interfaces. You don't have to know the entire API. However, every class and method on the exam is here, and a few more as well to make it a complete API. Among all the classes and interfaces, the Servlet interface is the central abstraction of the Servlet API. The specification ensures that all servlets implement this interface. This is usually done by extending a class that implements the Servlet interface. While there are two classes in the servlet API that implement the Servlet interface, GenericServlet and HttpServlet, we will focus only on HttpServlet. Because, it's the HttpServlet class methods that will appear on the exam.

The Servlet API defines the interfaces, classes, methods, fields, and constants that you will use to build servlets. The Web Component Developer Exam is filled with questions on this API. Therefore it is helpful to have an appendix which simply filters the most important parts of the Servlet 2.3 API.

Overview of the Servlet API

The Servlet 2.3 API consists of two packages: javax.servlet and javax.servlet.http. The base functionality is defined in the javax.servlet package whose classes and interfaces outline a generic, protocol-independent implementation. This means you can use it for non-Web applications, too. Of course, the exam targets the Web, so the HTTP protocol is the only one discussed in this blog. The javax.servlet.http interface defines classes and interfaces that are specific to the Hypertext Transfer Protocol (HTTP).

The javax.servlet Package

The javax.servlet package defines 12 interfaces, 7 classes, and 2 exceptions. These interfaces, classes, and exceptions are as follows.

Interfaces

Filter:- Preprocessor of the request before it reaches a servlet. It can also be a postprocessor of the response leaving a servlet. It can modify a request or response (for example, change headers), the request to a resource (a servlet or static content), or the response from a resource.
RequestDispatcher:- This is the servlet version of a redirect. It enables requests to be processed and then forwarded to other components of a Web application, such as another servlet, HTML file, or JSP file.
Servlet:- Defines the life-cycle methods that are implemented by all servlets.
ServletConfig:- This class has the methods for accessing the servlet configuration information such as the servlets name (from the web.xml file), the initialization parameters, and the ServletContext object.
ServletContext:- These methods enable your servlet to communicate with its servlet container. This is how you get the MIME type of a file, dispatch requests, or write to a log file. Notice that this information has application scope. The most important features of the ServletContext are application-scope attributes access, logging, and context initialization parameters.
ServletContextAttributeListener:- Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a Web application. Supports the handling of the ServletContextAttributeEvent class.
ServletContextListener:- An interface that supports the handling of the ServletContextEvent class. Defines a set of methods that a servlet uses to communicate with its servlet container. It can get the MIME type of a file, dispatch requests, or write to a log file. Notice that there is one context per “Web application” per Java Virtual Machine. The specification defines a “Web application” as a collection of servlets and content installed under a specific subset of the server's URL namespace, such as /catalog, and possibly installed via a .war file.
ServletRequest:- This interface forms the base for the class that provides client request information to a servlet. It is protocol-independent.
ServletResponse:- This interface forms the base for the class that represents the response sent from the servlet to the client.
SingleThreadModel:- An interface that ensures a given servlet handles only one request at a time.

Classes

GenericServlet:- An abstract class that implements ServletConfig. It defines a generic, protocol-independent servlet.
ServletContextAttributeEvent:- This is the event class for notifications about changes to the attributes of the servlet context of a Web application.
ServletContextEvent:- This is the event class for notifications about changes to the servlet context of a Web application (parent of ServletContextAttributeEvent).
ServletInputStream:- Provides an input stream for reading binary data from a client request. You can modify it; it already has the readLine method for reading data one line at a time.
ServletOutputStream:- An abstract class providing an output stream for sending binary data to the client. You print HTML, XML, or other output to the client using ServletOutputStream's print() and println() methods.
ServletRequestWrapper:- Provides a convenient implementation of the ServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet. This is where you can modify the behavior of request objects.
ServletResponseWrapper:- Provides a convenient implementation of the ServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet. This is where you can modify the behavior of response objects.

Exceptions

ServletException:- Extends java.lang.Exception to provide a base class for defining servlet-related extensions.
UnavailableException:- Extends ServletException to indicate that a servlet is temporarily or permanently unavailable.

Contents of the Interfaces, Classes & Exceptions in the javax.servlet package

In the previous segment, we saw the names of the interfaces, classes and exceptions in the javax.servlet package. Now, let us see what the contents of each of these entities are:

Interfaces

RequestDispatcher

The RequestDispatcher interface defines the forward() and include() methods for use as request wrappers. It enables requests to be processed and then forwarded to other elements of a Web application. It also allows the results of other application elements to be included in the response. A RequestDispatcher object is created with the path or name of the resource to be dispatched.

Servlet

The Servlet interface defines methods that are implemented by all servlets. A default implementation of these methods is provided by GenericServlet.
The following methods are used to control the servlet lifecycle:

init(ServletConfig config):- Invoked by the servlet container to put the servlet in service.
service(ServletRequest req, ServletResponse res):- Invoked by the servlet container to enable a servlet to respond to a request.
destroy():- Invoked by the servlet container to remove the servlet from service.
These methods provide access to servlet configuration information:
getServletConfig():- Returns the ServletConfig object that is associated with the servlet.
getServletInfo():- Returns the servlet's information string.

ServletConfig

The ServletConfig interface defines methods for accessing servlet configuration information. Configuration information is passed as a series of name-value pairs.

Methods also provide access to the servlet's name and ServletContext object:
getInitParameter(String name):- Returns the value of the specified parameter.
getInitParameterNames():- Returns an Enumeration of the names of the servlet's initialization parameters.
getServletContext():- Returns the ServletContext object corresponding to the servlet.
getServletName():- Returns the servlet's name.

ServletContext

The ServletContext interface defines methods for accessing application-scope attributes. It is limited to a single JVM, and therefore should not be used when clustering is implemented. The ServletContext methods provide access to objects that are placed in application scope:

getAttribute(String name):- Returns the object corresponding to the named attribute.
getAttributeNames():- Returns an Enumeration of the defined attribute names.
removeAttribute(String name):- Removes the attribute from the servlet context.
setAttribute(String name, Object object):- Sets the object associated with the specified attribute name.
getInitParameter(String name):- Returns the value of the named initialization parameter.
getInitParameterNames():- Returns an Enumeration the initialization parameter names.
getMajorVersion():- Returns the major version of the Servlet API supported by the servlet container.
getMimeType(String file):- Returns the MIME type of the specified file, if known.
getMinorVersion():- Returns the minor version of the Servlet API supported by the servlet container.
getRealPath(String path):- Translates a virtual path into a real path.
getServerInfo():- Returns the name and version of the servlet container on which the servlet is running.
getContext(String url):- Returns the ServletContext object that corresponds to the specified URL. The URL must be on the same server.
getNamedDispatcher(String name):- Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
getRequestDispatcher(String path):- Returns a RequestDispatcher object that acts as a wrapper for the resource located at the specified path.
getResource(String path):- Returns the URL of the resource that is mapped to the specified path.
getResourceAsStream(String path):- Returns the resource located at the specified path as an InputStream object.
log(String msg):- Writes the message to the servlet log file.
log(String message, Throwable throwable):- Writes the message to the servlet log file along with a stack trace for the Throwable object.

ServletContextAttributeListener

The ServletContextAttributeListener interface defines methods for handling the ServletContextAttributeEvent. These methods are as follows:

• attributeAdded(ServletContextAttributeEvent scab)
• attributeRemoved(ServletContextAttributeEvent scab)
• attributeReplaced(ServletContextAttributeEvent scab)

ServletContextListener

The ServletContextListener interface defines methods for handling the ServletContextEvent. The ServletContextEvent object represents the creation/destruction of a ServletContext.
The contextDestroyed() method handles the destruction of a ServletContext. Lastly, the contextInitialized() method handles the creation of a ServletContext object.

ServletRequest

The ServletRequest interface provides a protocol-independent definition of the methods used to access the information contained in a client request of a servlet. These methods provide access to nearly all of the information contained in the original request.

A ServletRequest object is created by the servlet container and made available to a servlet via its service() method. ServletRequest is extended by javax. servlet.http.HttpServletRequest.

ServletRequest defines several methods for accessing request data:

getAttribute(String name):- Returns the object associated with the attribute name.
getAttributeNames():- Returns an Enumeration of the request's attributes.
removeAttribute(String name):- Removes an attribute from this request.
setAttribute(String name, Object o):- Sets the value of an attribute of this request.
getParameter(String name):- Returns the value of the specified request parameter.
getParameterNames():- Returns an Enumeration of the names of the parameters of this request.
getParameterValues(String name):- Returns an array of the values of the specified request parameter.
getInputStream():- Provides a ServletInputStream that corresponds to the body of the request.
getReader():- Provides a BufferedReader that corresponds to the body of the request.
getCharacterEncoding():- Returns the character encoding used in the body of the request.
getContentLength():- Returns the length (in bytes) of the request body. Returns -1 if the length is not known.
getContentType():- Returns the MIME type of the body of the request, if known.
getProtocol():- Returns the name and version of the protocol used to make the request.
getScheme():- Returns the name of the scheme used to make this request (http, https, or ftp).
getServerPort():- Returns the port number associated with the request.
isSecure():- Returns a boolean indicating whether this request was made using a secure protocol, such as HTTPS.
getLocale():- Returns the Locale object corresponding to the Accept-Language header.
getLocales():- Returns an Enumeration of Locale objects based on the Accept-Language header.
getRemoteAddr():- Returns the IP address of the client.
getRemoteHost():- Returns the host name of the client or the IP address if the host name cannot be determined.
getRequestDispatcher(String path):- Returns a RequestDispatcher object that acts as a wrapper for the resource located at the specified path.
getServerName():- Returns the host name of the server that received the request.

ServletResponse

The ServletResponse interface encapsulates a response sent from the servlet to the client. A ServletResponse object is automatically created by the servlet container and passed to a servlet via its service method. ServletResponse defines several methods for configuring, assembling, and sending response information:

getCharacterEncoding():- Returns the name of the charset used for the MIME body sent in this response.
getLocale():- Returns the locale assigned to the response.
setContentLength(int len):- Sets the length of the content body (Content-Length header).
setContentType(String type):- Sets the content type of the response being sent to the client.
setLocale(java.util.Locale loc):- Sets the locale of the response and the appropriate headers.
getOutputStream():- Returns a ServletOutputStream for writing binary data to the client.
getWriter():- Returns a PrintWriter object for writing character data to the client.
flushBuffer():- Forces any content in the buffer to be written to the client.
getBufferSize():- Returns the actual buffer size used for the response.
isCommitted():- Returns a boolean indicating whether the response has been committed.
reset():- Clears any data that exists in the buffer as well as the status code and headers.
setBufferSize(int size):- Sets the buffer size for the body of the response.

SingleThreadModel

The SingleThreadModel interface is implemented by servlets that are required to handle a single request at a time. This interface is intended to make sure a single servlet thread is executed at a given point in time, providing thread safety. This interface defines no methods.
Classes

GenericServlet

The GenericServlet class defines a basic implementation of the Servlet interface in a protocol-independent manner. It also implements the ServletConfig and java.io.Serializable interfaces. It is extended by javax.servlet.http.HttpServlet.

ServletContextAttributeEvent

The ServletContextAttributeEvent is generated as the result of changes to the attributes of the servlet context. The getName() method returns the name of the attribute that was changed. The getValue() method returns the value of the changed attribute.

ServletContextEvent

The ServletContextEvent class is the parent class of ServletContextAttributeEvent. It provides notifications about changes to the servlet context of a Web application. The getServletContext() method provides access to the affected ServletContext object.

ServletInputStream

The ServletInputStream class is an abstract class that provides a stream for reading client request data. It extends java.io.InputStream. It is typically used with HTTP POST and PUT requests. An instance of this class is obtained via ServletRequest.getInputStream().

ServletOutputStream

The ServletOutputStream class is an abstract class that provides an output stream (binary) for sending response data. It extends java.io.OutputStream. An instance of this class is obtained via ServletResponse.getOutputStream().

ServletRequestWrapper

The ServletRequestWrapper class provides an implementation of the ServletRequest interface that can be extended and tailored to modify the way that a request is processed. A ServletRequest object is provided as an argument to the ServletRequestWrapper constructor. The methods of ServletRequestWrapper can be overridden to provide the wrapped effect. ServletRequestWrapper is extended by HttpServletRequestWrapper.

ServletResponseWrapper

The ServletResponseWrapper class provides an implementation of the ServletResponse interface that can be extended and tailored to modify the way that a response is processed. A ServletResponse object is provided as an argument to the ServletResponseWrapper constructor. The methods of ServletResponseWrapper can be overridden to provide the wrapped effect. ServletResponseWrapper is extended by HttpServletResponseWrapper.

Exceptions

ServletException

The ServletException exception extends java.lang.Exception to provide a base class for defining servlet-related extensions. The getRootCause() method provides access to the exception (if any) that results in the throwing of ServletException.

UnavailableException

The UnavailableException exception extends ServletException to indicate that a servlet is temporarily or permanently unavailable. The getUnavailableSeconds() method returns the number of seconds the servlet expects to be temporarily unavailable. The isPermanent() method returns a boolean value indicating whether the servlet is permanently unavailable.

The javax.servlet.http Package

The javax.servlet.http package defines eight interfaces and seven classes. These interfaces and classes are as follows:

Interfaces

The interfaces include the following:
HttpServletRequest:- Extends javax.servlet.ServletRequest to support HTTP.
HttpServletResponse:- Extends javax.servlet.ServletResponse to support HTTP.
HttpSession:- Defines methods that provide access to persistent session-state information.
HttpSessionActivationListener:- Implemented to handle the HttpSessionActivationEvent.
HttpSessionAttributeListener:- Implemented to handle the HttpSessionAttributeEvent.
HttpSessionBindingListener:- Implemented by objects that listen for HttpSessionBindingEvent events.
HttpSessionListener:- Implemented to handle the HttpSessionEvent.

Classes

The classes include the following:
Cookie:- Encapsulates HTTP cookies.
HttpServlet:- An abstract class that extends javax.servlet.GenericServlet to provide support for HTTP.
HttpServletRequestWrapper:- Provides the capability to wrap and modify incoming HttpServletRequest objects.
HttpServletResponseWrapper:- Provides the capability to wrap and modify outgoing HttpServletResponse objects.
HttpSessionBindingEvent:- Extends java.util.EventObject to define an event that is sent to an HttpSessionBindingListener when an object is bound or unbound from the current HttpSession.
HttpSessionEvent:- Parent class of HttpSessionBindingEvent.

Contents of the Interfaces, Classes & Exceptions in the javax.servlet.http package

In the previous segment, we saw the names of the interfaces and classes in the javax.servlet.http package. Now, let us see what the contents of each of these entities are:

Interfaces

HttpServletRequest

The HttpServletRequest interface extends javax.servlet.ServletRequest to support HTTP. An HttpServletRequest object is automatically created by the servlet container and provided as an argument to the HttpServlet's doXXX() methods.

HttpServletRequest provides numerous HTTP-specific methods for accessing the client's request. Some important methods are
getAuthType():- Returns the name of the authentication scheme used with the servlet.
getContextPath():- Returns the context path of the requested URL.
getCookies():- Returns an array containing all of the Cookie objects sent by the client.
getDateHeader(String name):- Returns the value of the date header as a long value.
getHeader(String name):- Returns the value of the specified request header.
getHeaderNames():- Returns an enumeration of all the header names that are associated with the request.
getHeaders(String name):- Returns an Enumeration of all the values of the specified request header.
getIntHeader(String name):- Returns the value of the specified request header as an int.
getMethod():- Returns the name of the HTTP method associated with the request.
getPathInfo():- Returns any extra path information associated with the request.
getPathTranslated():- Returns any extra path information after the servlet name but before the query string.
getQueryString():- Returns the query string that is associated with the request.
getRemoteUser():- Returns the login of the user making this request, if the user has been authenticated.
getRequestedSessionId():- Returns the session ID specified by the client cookie or URL-rewriting.
getRequestURI():- Returns the part of this request's URL from the protocol name up to the query string.
getServletPath():- Returns the part of this request's URL that calls the servlet.
getSession():- Returns the current session associated with this request, or if the request does not have a session, creates one.
getSession(boolean create):- Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. Otherwise, null is returned.
getUserPrincipal():- Returns a java.security.Principal object containing the name of the current authenticated user.
isRequestedSessionIdFromCookie():- Checks whether the requested session ID came in as a cookie.
isRequestedSessionIdFromURL():- Checks whether the requested session ID came in as part of the request URL.
isRequestedSessionIdValid():- Checks whether the requested session ID is still valid.
isUserInRole(String role):- Returns a boolean indicating whether the authenticated user is included in the specified logical “role.”

HttpServletResponse

The HttpServletResponse interface extends javax.servlet.ServletResponse to support HTTP. An HttpServletResponse object is automatically created by the servlet container and provided as an argument to HttpServlet's doXXX() methods.

HttpServletResponse also defines a number of response error code constants. It provides numerous methods for manipulating the response sent to the client.

The following are important HttpServletResponse methods:
addCookie(Cookie cookie):- Adds the specified cookie to the response.
addDateHeader(String name, long date):- Adds a response header with the given name and date.
addHeader(String name, String value):- Adds a response header with the given name and value.
addIntHeader(String name, int value):- Adds a response header with the given name and integer value.
containsHeader(String name):- Returns a boolean indicating whether the named response header has already been set.
encodeRedirectURL(String url):- Encodes the specified URL for use in the sendRedirect() method. It appends the session ID in it.
encodeURL(String url):- Encodes the specified URL by including the session ID in it.
sendError(int sc):- Sends an error response to the client using the specified status.
sendError(int sc, String msg):- Sends an error response to the client using the specified status code and descriptive message.
sendRedirect(String location):- Sends a temporary redirect response to the client.
setDateHeader(String name, long date):- Sets a response header with the given name and date.
setHeader(String name, String value):- Sets a response header with the given name and value.
setIntHeader(String name, int value):- Sets a response header with the given name and integer value.
setStatus(int sc):- Sets the status code for this response.

HttpSession

The HttpSession interface defines methods that provide access to persistent session-state information. These methods are used to get and set attributes into the session scope (getAttribute() and setAttribute()). Methods are also provided to get access to the session creation time, last access time, maximum timeout interval, and session ID. The invalidate() method is used to terminate an HTTP session.

HttpSessionActivationListener

The HttpSessionActivationListener interface defines methods for handling the HttpSessionActivationEvent. These methods are sessionDidActivate() and sessionWillPassivate().

HttpSessionAttributeListener

The HttpSessionAttributeListener interface defines methods for handling the HttpSessionAttributeEvent. These methods are attributeAdded(), attributeRemoved(), and attributeReplaced().

HttpSessionBindingListener

The HttpSessionBindingListener interface defines methods for objects that listen for HttpSessionBindingEvent events. The valueBound() method is invoked when an object is bound to an HttpSession. The valueUnbound() method is invoked when an object is unbound from an HttpSession.

HttpSessionContext

The HttpSessionContext interface was deprecated as of the Servlet 2.1 API. It is the predecessor of HttpSession.

HttpSessionListener

The HttpSessionListener interface defines methods for handling the HttpSessionEvent. The sessionCreated() method is used to handle the creation of a new HttpSession object. The sessionDestroyed() method handles the destruction of an HttpSession object.

Classes

Cookie

The Cookie class encapsulates HTTP cookies. It enables cookies to be retrieved or set. Cookies are retrieved via HttpServletRequest.getCookies(). Cookies are set via HttpServletResponse.addCookie(). Both version 0 (Netscape) and version 1 (RFC 2109) cookies are supported. Created cookies are version 0, by default. The Cookie class implements the Cloneable interface.

HttpServlet

The HttpServlet class is an abstract class that extends javax.servlet.GenericServlet to provide support for HTTP. It is extended to create custom servlets. It supports the HTTP GET, POST, PUT, DELETE, OPTIONS, and TRACE requests via protected methods of the form doGet(), doPost(), doPut(), doDelete(), doOptions(), and doTrace(). These methods take an HttpServletRequest object and an HttpServletResponse object as their parameters.

These protected doXXX()methods are overridden to handle specific request types. Remember that the service method dispatches to the appropriate doXXX() method.

HttpServletRequestWrapper

The HttpServletRequestWrapper class provides the capability to wrap and modify incoming HttpServletRequest objects. It extends ServletRequestWrapper and implements HttpServletRequest.
The request to be wrapped is passed to this class's constructor. Since this class implements the methods of HttpServletRequest, all of the request methods can then be invoked on the wrapped object. These methods can be overridden to produce the new wrapped results.

HttpServletResponseWrapper

The HttpServletResponseWrapper class provides the capability to wrap and modify outgoing HttpServletResponse objects. It extends ServletResponseWrapper and implements HttpServletResponse.

The response to be wrapped is passed to this class's constructor. Since this class implements the methods of HttpServletReponse, all of the response methods can then be invoked on the wrapped object. These methods can be overridden to produce the new wrapped results.

HttpSessionBindingEvent

The HttpSessionBindingEvent class extends HttpSessionEvent (which extends java.util.EventObject) to define an event that is sent to an HttpSessionBindingListener when an object is bound or unbound from the current HttpSession.

The String getName() method returns the attribute name of the object.
The HttpSession getSession() method returns the associated HttpSession object.

HttpSessionEvent

The HttpSessionEvent class is the parent class of HttpSessionBindingEvent. It is used to provide notifications of changes to sessions within a Web application. It defines one method, getSession(), that returns the HttpSession object of the affected session.

Exam Trivia:

I have covered almost everything you need to know about Servlets from the exam point of view in this chapter. Make sure to bookmark this page and revise it before you sit for the SCWCD exam. Even though it might look a bit boring to go through it once again, trust me you will not regret your decision. It will help you refresh whatever you learnt about Servlets and answer the exam questions better!!!

Previous Chapter: Self Test - Chapters 25 to 29

Next Chapter: Chapter 31 - JSP Introduction

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers