Section 1 - The Servlet Model

1.1 For each of the HTTP methods, GET, POST, and PUT, identify the corresponding method in the HttpServlet class.
1.2For each of the HTTP methods, GET, POST, and HEAD, identify triggers that might cause a browser to use the method, and identify benefits or functionality of the method.
1.3 For each of the following operations, identify the interface and method name that should be used:
  • Retrieve HTML form parameters from the request
  • Retrieve a servlet initialization parameter
  • Retrieve HTTP request header information
  • Set an HTTP response header; set the content type of the response
  • Acquire a text stream for the response
  • Acquire a binary stream for the response
  • Redirect an HTTP request to another URL
1.4 Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes:
  • request
  • Session
  • Context
1.5 Given a life-cycle method: init, service, or destroy, identify correct statements about its purpose or about how and when it is invoked.
1.6 Use a RequestDispatcher to include or forward to a Web resource.

Return to top


1.1 For each of the HTTP methods, GET, POST, and PUT, identify the corresponding method in the HttpServlet class.

J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses.

The HTTP methods are defined in the HttpServlet class. The structure is as follows:

public abstract class HttpServlet
       extends GenericServlet
       implements java.io.Serializable {
   ...
   doGet
   doPost
   doPut
   doDelete
   init
   destroy
   getServletInfo
   ...

public abstract class GenericServlet
           extends java.lang.Object
           implements Servlet, ServletConfig, java.io.Serializable

 
public interface Servlet {
    public void destroy()        
    public ServletConfig getServletConfig()         
    public java.lang.String getServletInfo()         
    public void init(ServletConfig config) throws ServletException      
    public void service(ServletRequest req, ServletResponse res) 
	    throws ServletException, java.io.IOException

Note: ServletException is a checked exception.

  1. GET:
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    ---for handling GET, conditional GET, and HEAD requests

    Called by the server (via the service method) to allow a servlet to handle a GET request.

    Overriding this method to support a GET request also automatically supports an HTTP HEAD request. A HEAD request is a GET request that returns no body in the response, only the request header fields. When overriding this method, read the request data, write the response headers, get the response’s writer or output stream object, and finally, write the response data. It’s best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

    The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body. Where possible, set the Content-Length header (with the javax.servlet.ServletResponse.setContentLength(int) method), to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer.

    The GET method should be safe, that is, without any side effects for which users are held responsible. For example, most form queries have no side effects. If a client request is intended to change stored data, the request should use some other HTTP method.

    The GET method should also be idempotent, meaning that it can be safely repeated. Sometimes making a method safe also makes it idempotent. For example, repeating queries is both safe and idempotent, but buying a product online or modifying data is neither safe nor idempotent. If the request is incorrectly formatted, doGet returns an HTTP "Bad Request" message.

  2. POST:
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    ---for handling POST request

    Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time and is useful when posting information such as credit card numbers.

    When overriding this method, read the request data, write the response headers, get the response’s writer or output stream object, and finally, write the response data. It’s best to include content type and encoding. When using a PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

    The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body. Where possible, set the Content-Length header (with the javax.servlet.ServletResponse.setContentLength(int) method), to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer.

    When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header. This method does not need to be either safe or idempotent. Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data or buying items online. If the HTTP POST request is incorrectly formatted, doPost returns an HTTP "Bad Request" message.

  3. PUT:
    public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    ---for handling PUT request

    Called by the server (via the service method) to allow a servlet to handle a PUT request. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.

    When overriding this method, leave intact any content headers sent with the request (including Content-Length, Content-Type, Content-Transfer-Encoding, Content-Encoding, Content-Base, Content-Language, Content-Location, Content-MD5, and Content-Range). If your method cannot handle a content header, it must issue an error message (HTTP 501 - Not Implemented) and discard the request.

    For more information on HTTP 1.1, see RFC 2068 (http://info.internet.isi.edu:80/in-notes/rfc/files/rfc2068.txt). This method does not need to be either safe or idempotent. Operations that doPut performs can have side effects for which the user can be held accountable.

    When using this method, it may be useful to save a copy of the affected URL in temporary storage. If the HTTP PUT request is incorrectly formatted, doPut returns an HTTP "Bad Request" message.

Return to top


1.2 For each of the HTTP methods, GET, POST, and HEAD, identify triggers that might cause a browser to use the method, and identify benefits or functionality of the method.

GET:

POST:

HEAD:

Return to top


1.3 For each of the following operations, identify the interface and method name that should be used:

  1. Retrieve HTML form parameters from the request

    ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest).

    The following methods are included in ServletRequest interface.

    1. java.util.Map getParameterMap()

      Returns a java.util.Map of the parameters of this request. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

      Returns: an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

    2. java.util.Enumeration getParameterNames()

      Returns an 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.

      Returns: an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters

    3. java.lang.String[] getParameterValues(java.lang.String name)

      Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. If the parameter has a single value, the array has a length of 1.

    4. java.lang.String getParameter(java.lang.String name)

      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 servlets, parameters are contained in the query string or posted form data.

      You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(String). If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned by getParameterValues.

      If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method.

  2. Retrieve a servlet initialization parameter

    interface ServletConfig --- A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

    1. java.lang.String getInitParameter(java.lang.String name)

      Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.

    2. java.util.Enumeration getInitParameterNames()

      Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.

  3. Retrieve HTTP request header information

    interface HttpServletRequest extends the ServletRequest interface to provide request information for HTTP servlets.

    1. long getDateHeader(java.lang.String name)

      Returns the value of the specified request header as a long value that represents a Date object. Use this method with headers that contain dates, such as If-Modified-Since.

      The date is returned as the number of milliseconds since January 1, 1970 GMT. The header name is case insensitive. If the request did not have a header of the specified name, this method returns -1. If the header can’t be converted to a date, the method throws an IllegalArgumentException.

    2. java.lang.String getHeader(java.lang.String name)

      Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. The header name is case insensitive. You can use this method with any request header.

    3. java.util.Enumeration getHeaderNames()

      Returns an enumeration of all the header names this request contains. If the request has no headers, this method returns an empty enumeration.

      Some servlet containers do not allow servlets to access headers using this method, in which case this method returns null

      Returns: an enumeration of all the header names sent with this request; if the request has no headers, an empty enumeration; if the servlet container does not allow servlets to use this method, null

    4. java.util.Enumeration getHeaders(java.lang.String name)

      Returns all the values of the specified request header as an Enumeration of String objects.

      Some headers, such as Accept-Language can be sent by clients as several headers each with a different value rather than sending the header as a comma separated list.

      If the request did not include any headers 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.

    5. int getIntHeader(java.lang.String name)

      Returns the value of the specified request header as an int. If the request does not have a header of the specified name, this method returns -1. If the header cannot be converted to an integer, this method throws a NumberFormatException. (which is an unchecked exception).

      The header name is case insensitive.

  4. Set an HTTP response header; set the content type of the response

    HttpServletResponse extends ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.

    The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).

    1. public void setDateHeader(java.lang.String name, long date)

      Sets a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.

    2. public void setHeader(java.lang.String name, java.lang.String value)

      Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.

    3. public void setIntHeader(java.lang.String name, int value)

      Sets a response header with the given name and integer value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.

    4. public void addDateHeader(java.lang.String name, long date)

      Adds a response header with the given name and date-value. The date is specified in terms of milliseconds since the epoch. This method allows response headers to have multiple values.

    5. public void addHeader(java.lang.String name, java.lang.String value)

      Adds a response header with the given name and value. This method allows response headers to have multiple values.

    6. public void addIntHeader(java.lang.String name, int value)

      Adds a response header with the given name and integer value. This method allows response headers to have multiple values.

    7. public void setLocale(java.util.Locale loc)

      Sets the locale of the response, setting the headers (including the Content-Type’s charset) as appropriate. This method should be called before a call to getWriter() . By default, the response locale is the default locale for the server.

    8. (ServletResponse) void setContentType(java.lang.String type)

      Sets the content type of the response being sent to the client. The content type may include the type of character encoding used, for example, text/html; charset=ISO-8859-4. If obtaining a PrintWriter, this method should be called first.

  5. Acquire a text stream for the response

    1. public java.io.PrintWriter ServletResponse.getWriter() throws java.io.IOException

      Returns a PrintWriter object that can send character text to the client. The character encoding used is the one specified in the charset= property of the setContentType(java.lang.String) method, which must be called before calling this method for the charset to take effect. If necessary, the MIME type of the response is modified to reflect the character encoding used. Calling flush() on the PrintWriter commits the response. Either this method or getOutputStream() may be called to write the body, not both.

     
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out.println("Here we go");
       ...
    

    Throws:

    java.io.UnsupportedEncodingException -(checked exception, subclass of IOException) 
           if the charset specified in setContentType cannot be used
    java.lang.IllegalStateException - (runtime exception)
           if the getOutputStream method has already been called for this response object
    java.io.IOException - 
           if an input or output exception occurred
    

    Note: here java.lang.IllegalStateException is a runtime exception. But javax.jms.IllegalStateException and javax.resource.spi.IllegalStateException are checked exceptions.

  6. Acquire a binary stream for the response

    1. public javax.servlet.ServletOutputStream ServletResponse.getOutputStream() throws java.io.IOException

      Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data. Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, not both.

    Throws:

        java.lang.IllegalStateException - (runtime exception)
    	    if the getWriter method has been called on this response
        java.io.IOException - if an input or output exception occurred
       

    For mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.

  7. Redirect an HTTP request to another URL

    1. public void HttpServletResponse.sendRedirect(java.lang.String location) throws java.io.IOException

      Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.
      If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.

      Throws:

      java.io.IOException - 
          If an input or output exception occurs
      java.lang.IllegalStateException - (runtime exception)
          If the response was committed
      
    2. public java.lang.String HttpServletResponse.encodeRedirectURL(java.lang.String url)

      Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is seperate from the encodeURL method.
      All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

      No exception thrown.

      Note: encodeRedirectUrl() method is deprecated, which is used before version 2.1

    3. public static final int HttpServletResponse.SC_TEMPORARY_REDIRECT
      Status code (307) indicating that the requested resource resides temporarily under a different URI.

    4. public static final int HttpServletResponse.SC_MOVED_TEMPORARILY
      Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource.

Return to top


1.4 Identify the interface and method to access values and resources and to set object attributes within the following three Web scopes:

  1. Request

    interface:

    1. ServletRequest
    2. HttpServletRequest

     
     public interface HttpServletRequest
             extends ServletRequest
    

    methods in ServletRequest:

    1. public java.lang.Object getAttribute(java.lang.String name)
      Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

      Attributes can be set two ways. The servlet container may set attributes to make available custom information about a request. For example, for requests made using HTTPS, the attribute javax.servlet.request.X509Certificate can be used to retrieve information on the certificate of the client. Attributes can also be set programatically using setAttribute(java.lang.String, java.lang.Object). This allows information to be embedded into a request before a RequestDispatcher call.

      Attribute names should follow the same conventions as package names. This specification reserves names matching java.*, javax.*, and sun.*.

    2. public java.util.Enumeration getAttributeNames()
      Returns an Enumeration containing the names of the attributes available to this request. This method returns an empty Enumeration if the request has no attributes available to it.

      Returns: an Enumeration of strings containing the names of the request's attributes

    3. public void setAttribute(java.lang.String name,java.lang.Object o)
      Stores an attribute in this request. Attributes are reset between requests. This method is most often used in conjunction with RequestDispatcher.

      Attribute names should follow the same conventions as package names. Names beginning with java.*, javax.*, and com.sun.*, are reserved for use by Sun Microsystems.

      If the value passed in is null, the effect is the same as calling removeAttribute(java.lang.String).

    4. public void removeAttribute(java.lang.String name)
      Removes an attribute from this request. This method is not generally needed as attributes only persist as long as the request is being handled.

      Attribute names should follow the same conventions as package names. Names beginning with java.*, javax.*, and com.sun.*, are reserved for use by Sun Microsystems.

    5. public java.lang.String getCharacterEncoding()
      Returns the name of the character encoding used in the body of this request. This method returns null if the request does not specify a character encoding

      Returns: a String containing the name of the chararacter encoding, or null if the request does not specify a character encoding

    6. public void setCharacterEncoding(java.lang.String env) throws java.io.UnsupportedEncodingException
      Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().

    7. public int getContentLength()
      Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. For HTTP servlets, same as the value of the CGI variable CONTENT_LENGTH.

      Returns: an integer containing the length of the request body or -1 if the length is not known

    8. public java.lang.String getContentType()
      Returns the MIME type of the body of the request, or null if the type is not known. For HTTP servlets, same as the value of the CGI variable CONTENT_TYPE.

      Returns: a String containing the name of the MIME type of the request, or null if the type is not known

    9. public java.lang.String getProtocol()
      Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets, the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.

      Returns: a String containing the protocol name and version number

    10. public java.lang.String getScheme()
      Returns the name of the scheme used to make this request, for example, http, https, or ftp. Different schemes have different rules for constructing URLs, as noted in RFC 1738.

      Returns: a String containing the name of the scheme used to make this request

    11. public java.lang.String getServerName()

      Returns the host name of the server that received the request. For HTTP servlets, same as the value of the CGI variable SERVER_NAME.

      Returns: a String containing the name of the server to which the request was sent

    12. public int getServerPort()
      Returns the port number on which this request was received. For HTTP servlets, same as the value of the CGI variable SERVER_PORT.

      Returns: an integer specifying the port number

    13. public java.lang.String getRemoteAddr()
      Returns the Internet Protocol (IP) address of the client that sent the request. For HTTP servlets, same as the value of the CGI variable REMOTE_ADDR.

      Returns: a String containing the IP address of the client that sent the request

    14. public java.lang.String getRemoteHost()
      Returns the fully qualified name of the client that sent the request. If the engine cannot or chooses not to resolve the hostname (to improve performance), this method returns the dotted-string form of the IP address. For HTTP servlets, same as the value of the CGI variable REMOTE_HOST.

      Returns: a String containing the fully qualified name of the client

    15. public java.util.Locale getLocale()
      Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. If the client request doesn't provide an Accept-Language header, this method returns the default locale for the server.

      Returns: the preferred Locale for the client

    16. public java.util.Enumeration getLocales()

      Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header. If the client request doesn't provide an Accept-Language header, this method returns an Enumeration containing one Locale, the default locale for the server.

      Returns: an Enumeration of preferred Locale objects for the client

    methods in the HttpServletRequest

    1. public java.lang.String getAuthType()
      Returns the name of the authentication scheme used to protect the servlet. All servlet containers support basic, form and client certificate authentication, and may additionally support digest authentication. If the servlet is not authenticated null is returned.

      Same as the value of the CGI variable AUTH_TYPE.

      Returns: one of the static members BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, DIGEST_AUTH (suitable for == comparison) indicating the authentication scheme, or null if the request was not authenticated.

    2. public java.lang.String getMethod()
      Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the value of the CGI variable REQUEST_METHOD.

      Returns: a String specifying the name of the method with which this request was made

    3. public java.lang.String getPathInfo()
      Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string. This method returns null if there was no extra path information. Same as the value of the CGI variable PATH_INFO.

      Returns: a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information

    4. public java.lang.String getPathTranslated()
      Returns any extra path information after the servlet name but before the query string, and translates it to a real path. Same as the value of the CGI variable PATH_TRANSLATED.

      If the URL does not have any extra path information, this method returns null. The web container does not decode this string.

      Returns: a String specifying the real path, or null if the URL does not have any extra path information

    5. public java.lang.String getContextPath()
      Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "". The container does not decode this string.

      Returns: a String specifying the portion of the request URI that indicates the context of the request

    6. public java.lang.String getQueryString()
      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. Same as the value of the CGI variable QUERY_STRING.

      Returns: a String containing the query string or null if the URL contains no query string. The value is not decoded by the container.

    7. public java.lang.String getRemoteUser()
      Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. Whether the user name is sent with each subsequent request depends on the browser and type of authentication. Same as the value of the CGI variable REMOTE_USER.

      Returns: a String specifying the login of the user making this request, or null

    8. public java.security.Principal getUserPrincipal()
      Returns a java.security.Principal object containing the name of the current authenticated user. If the user has not been authenticated, the method returns null.

      Returns: a java.security.Principal containing the name of the user making this request; null if the user has not been authenticated

    9. public java.lang.String getRequestedSessionId()

      Returns the session ID specified by the client. This may not be the same as the ID of the actual session in use. For example, if the request specified an old (expired) session ID and the server has started a new session, this method gets a new session with a new ID. If the request did not specify a session ID, this method returns null.

      Returns: a String specifying the session ID, or null if the request did not specify a session ID

    10. public java.lang.String getRequestURI()
      Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. The web container does not decode this String. For example: First line of HTTP request Returned Value
         POST /some/path.html HTTP/1.1  /some/path.html  
         GET http://foo.bar/a.html HTTP/1.0   /a.html  
         HEAD /xyz?a=b HTTP/1.1  /xyz  
         
      To reconstruct an URL with a scheme and host, use HttpUtils.getRequestURL(javax.servlet.http.HttpServletRequest).

      Returns: a String containing the part of the URL from the protocol name up to the query string

    11. public java.lang.StringBuffer getRequestURL()
      Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters. Because this method returns a StringBuffer, not a string, you can modify the URL easily, for example, to append query parameters. This method is useful for creating redirect messages and for reporting errors.

      Returns: a StringBuffer object containing the reconstructed URL

    12. public java.lang.String getServletPath()
      Returns the part of this request's URL that calls the servlet. This includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME.

      Returns: a String containing the name or path of the servlet being called, as specified in the request URL, decoded.

    13. public HttpSession getSession(boolean create)
      Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.

      If create is false and the request has no valid HttpSession, this method returns null.

      To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.

      Parameters: true - to create a new session for this request if necessary; false to return null if there's no current session

      Returns: the HttpSession associated with this request or null if create is false and the request has no valid session

    14. public HttpSession getSession()
      Returns the current session associated with this request, or if the request does not have a session, creates one.

      Returns: the HttpSession associated with this request

  2. Session

    interface HttpSession

    1. Enumeration getAttributeNames()
      returns empty enumeration if no attributes; IllegalStateException if session invalidated
    2. Object getAttribute(String name)
      returns null if no such object
    3. void setAttribute(java.lang.String name, java.lang.Object value)
    4. void removeAttribute(java.lang.String name)
    5. String getId()
      returns unique session identifier assigned by servlet container
    6. long getLastAccessedTime()
      time when client last sent a request associated with this session
    7. int getMaxInactiveInterval()
      returns number of seconds this session remains open between client requests; -1 if session should never expire
    8. void setMaxInactiveInterval(int interval)

  3. Context

    interface ServletContext

    1. Enumeration getAttributeNames()
      Returns an Enumeration containing the attribute names available within this servlet context.
    2. Object getAttribute(String name)
      Returns the servlet container attribute with the given name, or null if there is no attribute by that name.
    3. void setAttribute(String name, java.lang.Object object)
      Binds an object to a given attribute name in this servlet context.
    4. void removeAttribute(String name)
      Removes the attribute with the given name from the servlet context.
    5. ServletContext getContext(String uripath)
      Returns a ServletContext object that corresponds to a specified URL on the server.
    6. String getInitParameter(String name)
      Returns a String containing the value of the named context-wide initialization parameter, or null if does not exist.
    7. Enumeration getInitParameterNames()
      Returns names of the context's initialization parameters as Enumeration of String objects
    8. int getMajorVersion()
      Returns the major version of the Java Servlet API that this servlet container supports.
    9. int getMinorVersion()
      Returns the minor version of the Servlet API that this servlet container supports.
    10. String getMimeType(String file)
      Returns the MIME type of the specified file, or null if the MIME type is not known.
    11. RequestDispatcher getNamedDispatcher(String name)
      Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
    12. RequestDispatcher getRequestDispatcher(String path)
      Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
    13. String getRealPath(String path)
      Returns a String containing the real path for a given virtual path.
    14. java.net.URL getResource(String path)
      Returns a URL to the resource that is mapped to a specified path.
    15. InputStream getResourceAsStream(String path)
      Returns the resource located at the named path as an InputStream object.
    16. String getServerInfo()
      Returns the name and version of the servlet container on which the servlet is running.

4. Scopes

Return to top


1.5 Given a life-cycle method: init, service, or destroy, identify correct statements about its purpose or about how and when it is invoked.

Servlet interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:

  1. public void init(ServletConfig config) throws ServletException

    Called by the servlet container to indicate to a servlet that the servlet is being placed into service. The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.

    The servlet container cannot place the servlet into service if the init method throws a ServletException or does not return within a time period defined by the Web server

    Parameters: config - a ServletConfig object containing the servlet's configuration and initialization parameters

    Points

    • called after server constructs the servlet instance and before the server handles any requests
    • depending on the server and web app configuration, init() may be called at any of these times:
      1. when server starts,
      2. when the servlet is first requested, just before the service() method is invoked,
      3. at the request of the server administrator
    • if servlet specifies "load-on-startup/" in its web.xml file, then upon server startup, the server will create an instance of the servlet and call its init() method.
    • typically used to perform servlet initialization, e.g. loading objects used by servlet to handle requests, reading in servlet init parameters, starting a background thread.
    • servlet cannot be placed into service if init method throws ServletException or does not return within a server-defined time period
    • init() can only be called once per servlet instance

  2. public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException

    Parameters: req - the ServletRequest object that contains the client's request res - the ServletResponse object that contains the servlet's response

    Throws: ServletException - if an exception occurs that interferes with the servlet's normal operation java.io.IOException - if an input or output exception occurs

    Points

    • Called by the servlet container to allow the servlet to respond to a request.
    • Only called after the servlet's init() method has completed successfully.
    • The status code of the response always should be set for a servlet that throws or sends an error.
    • Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently.
    • Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet's class and instance variables.
  3. public void destroy()

    Points

  4. NOTES: Servlet reloading

Servlet Life Cycle in Servlet 2.3

Return to top


1.6 Use a RequestDispatcher to include or forward to a Web resource.

 
public interface javax.servlet.RequestDispatcher{
    public void forward(ServletRequest request,
                        ServletResponse response)
                        throws ServletException,
                        java.io.IOException
    public void include(ServletRequest request,
                        ServletResponse response)
                        throws ServletException,
                        java.io.IOException
}

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

To get a RequestDispatcher:

 
in the doGet(request, response) method
...
String url="/xxxx/xxx.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forword(request, response);
...

  1. include:

    public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException

    • Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.
    • The ServletRequest object has its path elements (e.g. attributes request_uri, context_path, and servlet_path) and parameters remain unchanged from the caller's.
    • The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
    • The request and response parameters must be the same objects as were passed to the calling servlet's service method.
    • The included resource must use the same output mechanism (e.g. PrintWriter or ServletOutputStream) as the caller's
    • Information can be passed to target using attached query string or using request attributes set with setAttribute() method.

  2. forward:

    public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException

    • Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response. The forwarding servlet generates no output, but may set headers.
    • The ServletRequest object has its path attributes adjusted to match the path of the target resource. Any new request parameters are added to the original.
    • forward() should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.
    • The request and response parameters must be the same objects as were passed to the calling servlet's service method.
    • Information can be passed to target using attached query string or using request attributes set with setAttribute() method.
    • forwarding to an html page containing relative url's included (e.g. "IMG" tags) is a bad idea, because forward() does not notify client about the directory from which the page is served, hence the links may be broken. Instead, use sendRedirect().

  3. Note: to get a request dispatcher object:
    • public RequestDispatcher ServletRequest.getRequestDispatcher(String path) - path may be relative, and cannot extend outside current servlet context
    • public RequestDispatcher ServletContext.getNamedDispatcher(String name) - name is the registered servlet name in web.xml file
    • public RequestDispatcher ServletContext.getRequestDispatcher(String path) - accepts only absolute paths, and not relative paths
Conditional Get
The HttpServlet interface defines the getLastModified method to support conditional GET operations. A conditional GET operation requests a resource be sent only if it has been modified since a specified time. In appropriate situations, implementation of this method may aid efficient utilization of network resources.

Return to top


Servlet Life Cycle
A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated and initialized, handles requests from clients, and how it is taken out of service. This life cycle is expressed in the API by the init, service, and destroy methods of the javax.servlet.Servlet interface that all servlets must implement directly, or indirectly through the GenericServlet or HttpServlet abstract classes.

Loading and Instantiation
The servlet container is responsible for loading and instantiating servlets. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request. When the servlet engine is started, needed servlet classes must be located by the servlet container. The servlet container loads the servlet class using normal Java class loading facilities. The loading may be from a local file system, a remote file system, or other network services.
After loading the Servlet class, the container instantiates it for use.

Initialization
After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC™ API based connections), and perform other one-time activities. The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. This configuration object allows the servlet to access name-value initialization parameters from the web application’s configuration information. The configuration object also gives the servlet access to an object (implementing the ServletContext interface) that describes the servlet’s runtime environment.

During initialization, the servlet instance can throw an UnavailableException or a ServletException. In this case the servlet must not be placed into active service and must be released by the servlet container. The destroy method is not called as it is considered unsuccessful initialization.
A new instance may be instantiated and initialized by the container after a failed initialization. The exception to this rule is when an UnavailableException indicates a minimum time of unavailability, and the container must wait for the period to pass before creating and initializing a new servlet instance.
In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.
Note that a servlet instance placed into service by a servlet container may handle no requests during its lifetime.

Return to top


End of Service
The servlet container is not required to keep a servlet loaded for any particular period of time. A servlet instance may be kept active in a servlet container for a period of milliseconds, for the lifetime of the servlet container (which could be a number of days, months, or years), or any amount of time in between.
When the servlet container determines that a servlet should be removed from service, it calls the destroy method of the Servlet interface to allow the servlet to release any resources it is using and save any persistent state. For example, the container may do this when it wants to conserve memory resources, or when it itself is being shut down.
Before the servlet container calls the destroy method, it must allow any threads that are currently running in the service method of the servlet to complete execution, or exceed a server defined time limit.
Once the destroy method is called on a servlet instance, the container may not route other requests to that instance of the servlet. If the container needs to enable the servlet again, it must do so with a new instance of the servlet’s class. After the destroy method completes, the servlet container must release the servlet instance so that it is eligible for garbage collection.

Return to top