HttpServlet Class in Java

Chapter 1 - The Servlet Technology Method

    HttpServlet Class in Java

  • HttpServlet class

    1. HttpServlet class

    The HttpServlet class extends the GenericServlet class and implements Serializable interface.

    That provides http specific methods such as doGet, doPost, doHead, doTrace etc.

    Methods of HttpServlet class

    There are many methods in HttpServlet class:

    1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.

    2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.

    3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container.

    4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container.

    5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container.

    6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.

    7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container.

    8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container.

    9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container.

    Servlet Lifecycle

    The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

    1. If an instance of the servlet does not exist, the web container can Loads the servlet class,Creates an instance of the servlet class andInitializes the servlet instance by calling the init method.

    2. Invokes the service method, passing request and response objects.needs to remove the servlet, the container finalizes the servlet by calling the servlet’s destroy method.

    Handling Servlet Lifecycle Events

    monitor and react to events in a servlet’s lifecycle by defining listener objects whose methods get invoked when lifecycle events occur. To use these listener objects,must define and specify the listener class.

    Defining the Listener Class

    Listener class is an implementation of a listener interface.the events that can be monitored and the corresponding interface that must be implemented.

    When a listener method is invoked, it is passed an event that contains information appropriate event.

    For example, the methods in the HttpSessionListener interface are passed an HttpSessionEvent, which contains an HttpSession.

    Servlet Lifecycle Events

    Listener Interface and Event Class:

    Web context Initialization and destruction javax.servlet.ServletContextListener and ServletContextEvent.

    Web context Attribute added, removed, replace javax.servlet.ServletContextAttributeListener and ServletContextAttributeEvent Session Creation, invalidation, activation, passivation, and timeout.

    javax.servlet.http.HttpSessionActivationListener,and HttpSessionEvent Session Attribute added, removed, or replaced javax.servlet.http.HttpSessionAttributeListener and HttpSessionBindingEvent

    Use the @WebListener annotation to define a listener to get events for various operations on the particular web application context.

    @WebListener must implement interfaces are:

    • javax.servlet.ServletContextListener
    • javax.servlet.ServletContextAttributeListener
    • javax.servlet.ServletRequestListener
    • javax.servlet.ServletRequestAttributeListener
    • javax.servlet..http.HttpSessionListener
    • javax.servlet..http.HttpSessionAttributeListener

    Examples:

    import javax.servlet.ServletContextAttributeListener;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    @WebListener()
    public class SimpleServletListener implements ServletContextListener,
            ServletContextAttributeListener {
        ...
    

    Handling Servlet Errors

    Any number of exceptions can occur when a servlet executes. When an exception occurs, the web container generates a default page.

    • A Servlet Exception Has Occurred
    • Creating and Initializing a Servlet

    Use the @WebServlet annotation to define a servlet component in a web application. This annotation is specified on a class and contains metadata about the servlet. The annotated servlet must specify at least one URL pattern. This is done by using the urlPatterns or value attribute on the annotation.

    otherwise use the urlPatterns attribute when other attributes are also used. Classes annotated with @WebServlet must extend the javax.servlet.http.HttpServlet class. For example, the  code defines a servlet with the URL pattern /report.

    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    
    @WebServlet("/report")
    public class MoodServlet extends HttpServlet {
        ...
    

    Writing Service Methods

    The Writing service provided by a servlet is implemented in the service method of a GenericServlet, in the doMethod methods (where Method can take the value Get,Delete, Options, Post, Put, or Trace) of an HttpServlet object.

    The term service method is used for any method in a servlet class that provides a service to a client.

    The general pattern for a service method is to extract information from the request, access external resources, and then populate the response, based on the information.

    1. Retrieve an output stream from the response.

    2. Fill in the response headers.

    3. Write any body content to the output stream.

    Response headers must always be set before the response has been committed. The web container will ignore any attempt to set or add headers after the response has been committed.

    Getting Information from Requests

    A request contains data passed between a client and the servlet. All requests implement the ServletRequest interface. This interface defines methods for accessing the following information:

    • Parameters are typically used to convey information between clients and servlets

    • Object-valued attributes, which are typically used to pass information between the web container and a servlet or between collaborating servlets

    • Information about the protocol used to communicate the request and about the client and server involved in the request

    • Information relevant to localization

    An HTTP request URL Path

    The request path is further composed of the following elements:

    Context path: A concatenation of a forward slash (/) with the context root of the servlet’s web application.

    Servlet path: The path that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

    Path info: The part of the request path that is not part of the context path or the servlet path.

    Query strings

    Query strings are composed of a set of parameters and values. Individual parameters are retrieved from a request by using the getParameter method. There are two ways to generate query strings.

    • A query string can explicitly appear in a web page.

    • A query string is appended to a URL when a form with a GET HTTP method is submitted.

    Constructing Responses

    A response contains data passed between a server and the client. All responses implement the ServletResponse interface. This interface defines methods that allow to:

    • Retrieve an output stream to use to send data to the client. To send character data, use the PrintWriter returned by the response’s getWriter method.

    To send binary data in a Multipurpose Internet Mail Extensions (MIME) body response, use the ServletOutputStream returned by getOutputStream. To mix binary and text data, as in a multipart response.

    • Indicate the content type (for example, text/html) being returned by the response with the setContentType(String) method. This method must be called before the response is committed. A registry of content type names is kept by the Internet Assigned Numbers Authority (IANA) at http://www.iana.org/assignments/media-types/.

    • Indicate whether to buffer output with the setBufferSize(int) method. By default, any content written to the output stream is immediately sent to the client. Buffering allows content to be written before anything is sent back to the client.

    • Set localization information, such as locale and character encoding.

    HTTP response objects, javax.servlet.http.HttpServletResponse, have fields representing HTTP headers, such as the following:

    • Status codes, which are used to indicate the reason a request is not satisfied or that a request has been redirected.

    • Cookies, which are used to store application-specific information at the client. Sometimes, cookies are used to maintain an identifier for tracking a user’s session.

    Filtering Requests and Responses

    A filter is an object that can transform the header and content of a request or response. Filters differ from web components in that filters.do not create a response.

    filter should not have any dependencies on a web resource for which it is acting as a filter;it can be composed with more than one type of web resource.

    The main tasks that a filter can perform are as follows:

    • Query the request and act accordingly.

    • Block the request-and-response pair from passing any further.

    • Modify the request headers and data.

    • Interact with external resources.

    Applications of filters include authentication, logging, image conversion, data compression, encryption, tokenizing streams, XML transformations, and so on.application containing the component is deployed and is instantiated when a web container loads the component.

© 2015 by Learncertification All Rights Reserved. The certification names are the trademarks of their respective owners. Terms & Privacy Policy