Tuesday, May 1, 2012


Servlet Overview and Architecture

  • client sends an HTTP request to the server . The server receives the request and directs it to be processed by the appropriateservletThe servlet does its processing, which may include interacting with a database or other server-side components such as other servlets, JSPs or Enterprise Java-Beans. The servlet returns its results to the client—normally in the form of an HTML, XHTML or XML document to display in a browser, but other data formats, such as images and binary data, can be returned.
Servlet Life Cycle
  • All servlets must implement the Servlet interface. As with many key applet methods, the methods of interface Servlet are invokedautomatically by the server. This interface defines five methods :
void init( ServletConfig config )
This method is automatically called once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet.
ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes).
String getServletInfo()
This method is defined by a servlet programmer to return a String containing servlet information such as the servlet’s author and version.
void service( ServletRequest request, ServletResponse response )
The servlet container calls this method to respond to a client request to the servlet.
void destroy()
This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here.
  • A servlet’s life cycle begins when the servlet container loads the servlet into memory—normally, in response to the first request that the servlet receives.
  • Before the servlet can handle that request, the servlet container invokes the servlet’s init method.
  • After init completes execution, the servlet can respond to its first request.
  • All requests are handled by a servlet’s service method, which receives the request, processes the request and sends a response to the client.
  • During a servlet’s life cycle, method service is called once per request. Each new request typically results in a new thread of execution (created by the servlet container) in which method service executes.
  • Starting a new thread for each request is more efficient than starting an entirely new process,
  • When the servlet container terminates the servlet, the servlet’s destroy method is called to release servlet resources.
  • The servlet packages define two abstract classes that implement the interface Servlet—class GenericServlet (from the packagejavax.servlet) and class HttpServlet (from the package javax.servlet.http). These classes provide default implementations of all theServlet methods. Most servlets extend either GenericServlet or HttpServlet and override some or all of their methods.
  • The key method in every servlet is service, which receives both a ServletRequest object and a ServletResponse object. These objects provide access to input and output streams that allow the servlet to read data from the client and send data to the client. These streams can be either byte based or character based. If problems occur during the execution of a servlet, either ServletExceptions or IOExceptionsare thrown to indicate the problem.
  • Servlets can implement tagging interface javax.servlet.SingleThreadModel to indicate that only one thread of execution may enter method service on a particular servlet
    instance at a time. When a servlet implements SingleThreadModel, the servlet container can create multiple instances of the servlet to handle multiple requests to the servlet
    in parallel. In this case, you may need to provide synchronized access to shared resources used by method service.
HttpServlet Class
  • public abstract class HttpServlet extends GenericServlet
  • GenericServlet implements interface javax.servlet.Servlet.
  • Class HttpServlet overrides method service to distinguish between the typical requests received from a client Web browser.
HTTP request types
 description
 Common uses
getA get request gets (or retrieves) information from a server.retrieve content of a specified URL such as HTML , XHTML document (i.e., a Web page) or an image.
postA post request posts (or sends) data to a server.send information, such as authentication information or data from a form that obtains user input, to a server.
  • Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client, respectively.
  • These methods are called by the service method, which is called when a request arrives at the server.
  • Method service first determines the request type, then calls the appropriate method for handling such a request.
public void service(ServletRequest req,ServletResponse res)
Dispatches client requests to the protected service method. There's no need to override this method.
protected void service(HttpServletRequest req,
HttpServletResponse resp)
Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of the Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) method. There's no need to override this method.
Do not override method service in an HttpServlet subclass. Doing so prevents the servlet from distinguishing between request types.
  • Methods of class HttpServlet that respond to the other request types are shown in the next figure. They all receive parameters of typeHttpServletRequest and HttpServletResponse and return void.
  • Methods doGet and doPost receive as arguments an HttpServletRequest object and an HttpServletResponse object that enable interaction between the client and the server.
    • The methods of HttpServletRequest make it easy to access the data supplied as part of the request.
    • The HttpServletResponse methods make it easy to return the servlet’s results to the Web client.
MethodDescription
doDeleteCalled in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers, because of its inherent security risks (i.e., the client could delete a file that is critical to the execution of the server or an application).
doOptionsCalled in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the
version of HTTP (1.0 or 1.1) and the request methods the server supports.
doPutCalled in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers,
because of its inherent security risks (i.e., the client could place an executable application on the server, which, if executed, could damage the server—
perhaps by deleting critical files or occupying resources).
doTrace
Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically
returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).


HttpServletRequest Interface
  • Every call to doGet or doPost for an HttpServlet receives an object that implements interface HttpServletRequest.
  • The Web server that executes the servlet creates an HttpServletRequest object and passes this to the servlet’s service method (which, in turn, passes it to doGet or doPost)
  • This object contains the request from the client. A variety of methods are provided to enable the servlet to process the client’s request. Some of these methods are from interface ServletRequest—the interface that HttpServletRequest extends.
MethodDescription
String getParameter( String name )Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name.
Enumeration getParameterNames()Returns the names of all the parameters sent to the servlet as part of a post request.
String[] getParameterValues( String name )For a parameter with multiple values, this method returns an array of Strings containing the values for a specified servlet parameter.
Cookie[] getCookies()Returns an array of Cookie objects stored on the client by the server. Cookies can be used to uniquely identify clients to the servlet.
HttpSession getSession( boolean create )Returns an HttpSession object associated with the client’s current browsing session. An HttpSession object can be created by this method (true argument) if an HttpSession object does not already exist for the client. HttpSession objects can be used in similar ways to Cookies for uniquely identifying clients.

 
HttpServletResponse Interface
  • This object contains the response from the server.
void addCookie( Cookie cookie )Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client.
ServletOutputStream getOutputStream()Obtains a byte-based output stream for sending binary data to the client.
PrintWriter getWriter()Obtains a character-based output stream for sending text data to the client.
void setContentType( String type )Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page. For more information on

No comments:

Post a Comment