Wednesday 29 July 2015

Servlet Implementation

To implement the servlet in the program there are basically 4 ways means we can use any one from following four classes or interfaces to create a servlet program.

  • Servlet interface
  • GenericServlet class
  • HttpServlet class
  • SingleThreadModel interface

Servlet Interface

All the user defined servlets should inherit the servlet interface. It is having following methods which defines the life cycle of servlet. 

init():
It is called by servlet container to initialize the servlet itself. It is called once only when servlet engine loads the servlet. It finishes its work before the service method starts for request and response. It’s having one parameter with it, which is an object of ServletConfig interface for start up configuration and initialization parameters which returned through getServletConfig(). If any error occurs with initialization(fatal error) it throws an UnavailableException.

Syntax:
public abstract void init(ServletConfig config)throws ServletException,UnavaliableException

getServletConfig():
It returns the ServletConfig object which contains initialization parameter and start up configuration of servlet. It is passes as a parameter in the init().

Syntax:
public abstract void getServletConfig()

service():
It is used to read the client request and write the response data to the client. It passes two parameters with it first object of ServletRequest interface and second the object of ServletResponse interface. The requests object having information related to client request and parameters provided by the client and response object contains the information which is sent back to the client based on request. This method is called after the initialization is completed. If any error occurs during the request and response or input and output it throws an IOException and ServletException.

Syntax:
public abstract void service(ServletRequest req,ServletResponse res)throws IOException,ServletException

getServletInfo():
It returns the basic information related to the servlet such as author name, version, copyright etc.

Syntax:
public abstract String getServletInfo()

destroy():
This method is called by servlet container automatically when the objects or resources like memory, thread etc. needs to be destroyed or servlet stops its execution.

Syntax:
public abstract void destroy()


GenericServlet Class

The GenericServlet class belongs to javax.servlet package. It implements the Servlet,ServletConfig and Serializable interface in it. It defines the generic independent servlet it means that it is extended to provide the protocol based things like FTP, SMTP protocols but it is not having HTTP protocol facility. So most probably with web application we need to extend the HttpServlet class.
GenericServlet class provides the implementation of Servlet interface because in the most of the classes they are required to use service() to handle the requests and responses. It is having most of the methods which are there with the super interfaces except log().


 Methods of GenericServlet class

init():
It is called by servlet container to initialize the servlet itself. It is called once only when servlet engine loads the servlet. It finishes its work before the service method starts for request and response. It’s having one parameter with it, which is an object of ServletConfig interface for start up configuration and initialization parameters which returned through getServletConfig(). If any error occurs with initialization(fatal error) it throws an UnavailableException.

Syntax:
public abstract void init(ServletConfig config)throws ServletException,UnavaliableException

service():
It is used to read the client request and write the response data to the client. It passes two parameters with it first object of ServletRequest interface and second the object of ServletResponse interface. The requests object having information related to client request and parameters provided by the client and response object contains the information which is sent back to the client based on request. This method is called after the initialization is completed. If any error occurs during the request and response or input and output it throws an IOException and ServletException.

Syntax:
public abstract void service(ServletRequest req,ServletResponse res)throws IOException,ServletException
 
destroy():
This method is called by servlet container automatically when the objects or resources like memory, thread etc. needs to be destroyed or servlet stops its execution.

Syntax:
public abstract void destroy()

log():
GenericServlet class provides the log() method to write the server log file. It is an overloaded method which we can use in two ways, first way log(String str)method writes servlet name and message to web containers log file and other method log(String str,Throwable t), writes servlet name, string str and the exception stack trace of given throwable exception to web containers log file.

Syntax:
public void log(String str)
public void log(String str, Throwable t)

getInitParameter():
It is used to get the initialization parameter. If the parameter does not exist it returns null.

Syntax:
public String getInitParameter(String str)

getInitParameterNames():
It returns the name of the initialization parameter names in the form of Enumeration.

Syntax:
public Enumeration getParameterNames()

getServletContext():
It returns the object of ServletContext.

Syntax:
public ServletContext getServletContext()

getServletName():
It returns name of the servlet.

Syntax:
public String getServletName()

Single Thread Model

In the CGI a single instance creates multiple threads in order to process multiple request and response.
In the past also a single instance of a servlet creates multiple threads for multiple request and response.
In this process the shared non local variables must be synchronized in the order to prevent data inconsistency. But synchronization is implemented at the cost of system performance because thread waits in a queue for the current thread to complete its job. Therefore synchronizing the code increases time to perform a single task, it downs the performance of the system. In certain cases synchronization may not be appropriate method to implement thread safely. So, in such case we need to implement the SingleThreadModel.

SingleThreadModel is implemented by SingleThread interface. It ensures that servlets handle only one request at a time. This interface has no methods. If a servlet implements  this interface, you are guaranteed that no two threads will execute concurrently in the servlet’s service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet. Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used.

HttpServlet Class

The HttpServlet class extends GenericServlet class. It is commonly used by programmers when developing servlets that receive and process HTTP requests, because it is having HTTP functionality.


Methods of HttpServet class

doGet():doGet() is called by the server via the service() to handle an HTTP GET request. A GET request allows a client to send form data to a server. With the GET request, the form data is attached to the end of the URL sent by the browser to the server as a query string. The amount of form data that can be sent is limited to the maximum length of the URL.

Syntax:
public void doGet(HttpServeltRequest req,HttpServletResponse res)throws IOException,ServletException

doPost():
doPost() is called by the server via the service() to handle an HTTP POST request. A POST request allows a client to send form data to a server. With the POST request, the form data is sent to the server separately instead of being appended to the URL. This allows a large amount of form data to be sent.

Syntax:
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

doDelete():
doDelete() is called by the server via the service() to handle an HTTP DELETE request. A DELETE request allows a client to remove a document of web page from a server.

Syntax:
public void doDelete(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

doOption():
doOption() is called by the server via the service() to handle an HTTP OPTIONS request. An OPTIONS request determines which HTTP methods the server supports and sends the information back to the client by way of header.

Syntax:
public void doOption(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

doPut():
doPut() is called by the server via service() to handle an HTTP PUT request. A PUT request allows a client to place a file on the server and is conceptually similar to sending the file to the server via FTP.

Syntax:
public void doPut(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

doTrace():
doTrace() is called by the server via the service() to handle an HTTP TRACE request. A TRACE request returns the headers sent with the TRACE request back to the client. This can be useful for debugging purposes.  This method is rarely overridden.

Syntax:
public void doTrace(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

Servlet Life Cycle

To execute the servlet program with servlet life cycle servlet container calls different methods of servlet interface on different stage. Three methods are central to the life cycle of a servlet.
  • Init()
  • Service()
  • Destroy()

Figure of Servlet Life Cycle

 

These above three methods are implemented by every servlet and are invoked at specific times by server. Let’s take a look how servlet performs its life cycle. Assume user enters a URL to a browser. The browser generates an HTTP Request for the URL and send to the server. Then, Server receives the HTTP Request. The server maps this request to a particular servlet. The server is dynamically retrieved and loaded into the address space of the server. The server invokes the init() of the servlet. This method invoked only when the servlet is first loaded into memory. You will see that initialization parameters can be passed to the servlet so that it may configure itself. The server invokes the servlet’s service(), which is called by the HTTP request. You will see that the servlet can read data that has been provided in the HTTP request, and may also formulate an HTTP response for the client.
The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service() is called for each HTTP request. Finally, the server may decide to unload the servlet from its memory. The servlet calls destroy().
The memory allocated for the servlet and its objects can then be garbage collected.

Servlet Exceptions

Java provides various classes for a servlet to handle any exception occurred during execution of a servlet. A servlet throws an exception when it finds difficulties. The javax.servlet defines exceptions.
  • ServletException
  • UnavailableException

ServletException

ServletException indicates that a servlet problem has occurred. The general syntax of ServletException class is:
  • public class ServletException extends Exception
It has following constructors:
  • public ServletException()
  • public ServletException(String msg)
  • public ServletException(String msg, Throwable rootCause)
  • public ServletException(Throwable rootCause)
getRootCause() method of the ServletException class returns the exception that caused this servlet exception.

UnavailableException class

UnavailableException extends ServletException. It shows that a servlet is temporarily or permanently unavailable. When it throws unavailable exception, something is wrong with it, it can not requests until some action is taken. A servlet is temporarily unavailable if it can not handle requests momentarily due to some system wide problem. Servlet container can safely treat both types of unavailable exceptions in the same way. However, treating temporary unavailability effectively makes the servlet container more robust.
Specifically, the servlet container might block requests to the servlet or filter for a period of time suggested by the exception, rather than rejecting them until the servlet container restarts.
General syntax:

public class UnavailableException extends ServletException

Constructors:
UnavailableException()
UnavailableException(String msg)
UnavailableException(String msg,int second)
Methods:
getUnavailableSecond(): it returns the no of seconds the servlet expects to be temporarily available.
getServlet():    it returns the servlet that threw this exception or null if the servlet instance was not provided to the constructor.
isPermanent():  it indicates that the servlet is permanently unavailable or not.


ServletRequest Interface

ServletRequest interface is a member javax.servlet package. Public interface ServletRequest defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the service(). An object of ServletRequest provides data including parameter name, attributes, an input stream and values. There are many interfaces that extends ServletRequest interface and can provide additional protocol specific data. For example, HTTP data is provided by HttpServletRequest.

HttpServletRequest Interface

A public interface HttpServletRequest extends ServletRequest interface and it is a member of javax.servlet.http package. It is used to provide request information for HTTP servlets. The servlet container creates an HttpServletRequest object and passes it as an argument to the service method. 

Method of ServletRequest interface and HttpServletRequest interface.
  • setAttribute():
    • It is a method of ServletRequest interface and it stores an attribute in this request. Attributes are reset between requests. This methods is most often used in conjunction with RequestDispatcher.
    • Syntax:
      • void setAttribute(String nm,Object obj)
  • getParameter():
    • It is a method of ServletRequest interface and it returns the value of a request parameter as a String, or null if the parameter does not exist.
    • Request parameters are extra information sent with the request. For HTTP servlet, parameters are contained in the query string or posted form data.
    • We can only use this method when we are sure the parameter has only one value.
    • Syntax:
      • String getParameter(String nm)
  • getParameterNames():
    • It is a method of ServletRequest interface and it returns Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration.
    • Syntax:
      • Enumeration getParameterNames()
  • getParameterValues():
    • It is a method of ServletRequest interface and it returns an array of String objects with all the values that the given request parameter has, or null if the parameter does not exist.
    • If the parameter has a single value, a length of array is 1.
    • Syntax:
      • String[] getParameterValues(String nm)
  • getAttribute():
    • It is a method of ServletRequest interface and it returns the value of the named attrubute as an object, or null if no attribute of the given name exists.
    • Syntax:
      • Object getAttribute(String nm)
  • getAttributeNames():
    • It is a method of ServletRequest interface and it returns an Enumeration containing the names of the attribute available to this request. This method returns an empty Enumeration if the request has no attributes available to it.
    • Syntax:
      • Enumeration getAttributeNames()
  • getRemoteHost():
    • It is a method of ServletRequest interface and it returns the fully qualified name of the client or the last proxy that sent the request.
    • If  the engine can not resolve the host name to improve performance, this method returns the dotted – string in the form of IP address.
    • Syntax:
      • String getRemoteHost()
  • getRemoteAddr():
    • It is a method of ServletRequest interface and it returns the IP address of the client or last proxy that sent the request.
    • Syntax:
      • String getRemoteAddr()
  • getHeaders():
    • The HttpServletRequest interface provides to return all the values of the specified request header as an Enumeration of String objects. If the request did not include any header of the specified name, this method returns an empty Enumeration.
    • The header name is case insensitive. You can use this method with any request header.
    • Syntax:
      • Enumeration getHeaders()
  • getCookies():
    • The HttpServletRequest interface provides the getCookies() to obtain an array of cookies that are present in the request. This method returns null if no cookies were sent.
    • The cookies are data sent from the client to the server on every request that the client makes. So, getCookies() returns the contents of the Cookie header, passed and stored in an array of Cookie object.
    • Syntax:
      • Cookies[] getCookies()
  • getQueryString():
    • The HttpServletRequest interface returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a query string.
    • Syntax:
      • String getQueryString()
  • getSession():
    • The HttpServletRequest interface returns the current session associated with this request or if the request does not have a session, creates one.
    • Syntax:
      • HttpSession getSession()

ServletResponse Interface

A public interface ServletResponse is a member of javax.servlet package. It defines an object to assist a servlet in sending a response to the client. The container of the servlet creates a ServletResponse object and passes it as an argument to its service method. For binary data in a MIME(Multipurpose Internet Mail Extension) body response ServletOutputStream is returned by getOutputStream(). But for Character data, use the PrintWriter object returned by getWriter(). The ServletResponse interface is implemented by the server. It enables a servlet to create a response for a client. There are many interfaces that extend ServletResponse interface and can provide additional protocol specific data.

HttpServletResponse Interface

A public interface HttpServletResponse extends ServletResponse interface. HttpServletResponse interface provides HTTP specific functionalities in sending response.

Methods of ServletResponse & HttpServletResponse

  • setContentType():
    • It is a method of ServletResponse interface, which is used to set the content type of the response being sent to the client.
    • The content type may include the type of character encoding used.
    • Syntax:
      • void setContentType(String type)
  • setHeader():
    • It is a method of HttpServletResponse interface and is used to set a response header with the given name and value.
    • If the header had already been set, the new value overwrites the previous one.
    • We can use containsHeader() to test for the presence of a header before setting its value.
    • Syntax:
      • void setHeader(String nm,String value)

No comments:

Post a Comment