Thursday 30 March 2017

Reading Servlet Parameters & The javax.servlet.http Package - Java Tutorials

Reading Servlet Parameters

The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a client request. We will develop a servlet that illustrates their use. The example contains two files. A Web page is defined in PostParameters.htm and a servlet is defined in PostParametersServlet.java.

The HTML source code for PostParameters.htm is shown in the following listing. It defines a table that contains two labels and two text fields. One of the labels is Employee and the other is Phone. There is also a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTP POST request.

  <html>
  <body>
  <center>
  <form name="Form1"
    method="post"
    action="http://localhost:8080/examples/servlet/PostParametersServlet">
  <table>
  <tr>
    <td><B>Employee</td>
    <td><input type=textbox name="e" size="25" value=""></td>
  </tr>
  <tr>
    <td><B>Phone</td>
    <td><input type=textbox name="p" size="25" value=""></td>
  </tr>
  </table>
  <input type=submit value="Submit">
  </body>
  </html>

The source code for PostParametersServlet.java is shown in the following listing. The service( ) method is overridden to process client requests. The getParameterNames( ) method returns an enumeration of the parameter names. These are processed in a loop. You can see that the parameter name and value are output to the client. The parameter value is obtained via the getParameter( ) method.

  import java.io.*;
  import java.util.*;
  import javax.servlet.*;

  public class PostParametersServlet
  extends GenericServlet {

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

      // Get print writer.
      PrintWriter pw = response.getWriter();

      // Get enumeration of parameter names.
      Enumeration e = request.getParameterNames();

      // Display parameter names and values.
      while(e.hasMoreElements()) {
        String pname = (String)e.nextElement();
        pw.print(pname + " = ");
        String pvalue = request.getParameter(pname);
        pw.println(pvalue);
      }
      pw.close();
    }
  }

Compile the servlet and perform these steps to test this example:
  1. Start Tomcat (if it is not already running).
  2. Display the Web page in a browser.
  3. Enter an employee name and phone number in the text fields.
  4. Submit the Web page.

After following these steps, the browser will display a response that is dynamically generated by the servlet.




The javax.servlet.http Package

The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet developers. You will see that its functionality makes it easy to build servlets that work with HTTP requests and responses. The following table summarizes the core interfaces that are provided in this package:

Interface  --  Description

HttpServletRequest:  Enables servlets to read data from an HTTP request.

HttpServletResponse:  Enables servlets to write data to an HTTP response.

HttpSession:  Allows session data to be read and written.

HttpSessionBindingListener:  Informs an object that it is bound to or unbound from a session.

The following table summarizes the core classes that are provided in this package. The most important of these is HttpServlet. Servlet developers typically extend this class in order to process HTTP requests.

Class  --  Description

Cookie:  Allows state information to be stored on a client machine.

HttpServlet:  Provides methods to handle HTTP requests and responses.

HttpSessionEvent:  Encapsulates a session-changed event.

HttpSessionBindingEvent:  Indicates when a listener is bound to or unbound from a session value, or that a session attribute changed.

The HttpServletRequest Interface
The HttpServletRequest interface is implemented by the server. It enables a servlet to obtain information about a client request.

Various Methods Defined by HttpServletRequest

String getAuthType( ):  Returns authentication scheme.

Cookie[ ] getCookies( ):  Returns an array of the cookies in this request.

long getDateHeader(String field):  Returns the value of the date header field named field.

String getHeader(String field):  Returns the value of the header field named field.

Enumeration getHeaderNames( ):  Returns an enumeration of the header names.

int getIntHeader(String field):  Returns the int equivalent of the header field named field.

String getMethod( ):  Returns the HTTP method for this request.

String getPathInfo( ):  Returns any path information that is located after the servlet path and before a query string of the URL.

String getPathTranslated( ):  Returns any path information that is located after the servlet path and before a query string of the URL after translating it to a real path.

String getQueryString( ):  Returns any query string in the URL.

String getRemoteUser( ):  Returns the name of the user who issued this request.

String getRequestedSessionId( ):  Returns the ID of the session.

String getRequestURI( ):  Returns the URI.

StringBuffer getRequestURL( ):  Returns the URL.

String getServletPath( ):  Returns that part of the URL that identifies the servlet.

HttpSession getSession( ):  Returns the session for this request. If a session does not exist, one is created and then returned.

HttpSession getSession(boolean new):  If new is true and no session exists, creates and returns a session for this request. Otherwise, returns the existing session for this request.

boolean isRequestedSessionIdFromCookie( ):  Returns true if a cookie contains the session ID. Otherwise, returns false.

boolean isRequestedSessionIdFromURL( ):  Returns true if the URL contains the session ID. Otherwise, returns false.

boolean isRequestedSessionIdValid( ):  Returns true if the requested session ID is valid in the current session context.

The HttpServletResponse Interface
The HttpServletResponse interface is implemented by the server. It enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. For example, SC_OK indicates that the HTTP request succeeded and SC_NOT_FOUND indicates that the requested resource is not available.

Various Methods Defined by HttpServletResponse

void addCookie(Cookie cookie):  Adds cookie to the HTTP response.

boolean containsHeader(String field):  Returns true if the HTTP response header contains a field named field.

String encodeURL(String url):  Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of url. Otherwise, returns url. All URLs generated by a servlet should be processed by this method.

String encodeRedirectURL(String url):  Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of url. Otherwise, returns url. All URLs passed to sendRedirect( ) should be processed by this method.

void sendError(int c) throws IOException:  Sends the error code c to the client.

void sendError(int c, String s) throws IOException:  Sends the error code c and message s to the client.

void sendRedirect(String url) throws IOException:  Redirects the client to url.

void setDateHeader(String field, long msec):  Adds field to the header with date value equal to msec (milliseconds since midnight, January 1, 1970, GMT).

void setHeader(String field, String value):  Adds field to the header with value equal to value.

void setIntHeader(String field, int value):  Adds field to the header with value equal to value.

void setStatus(int code):  Sets the status code for this response to code.

The HttpSession Interface
The HttpSession interface is implemented by the server. It enables a servlet to read and write the state information that is associated with an HTTP session. All of these methods throw an IllegalStateException if the session has already been invalidated.

The Methods Defined by HttpSession

Object getAttribute(String attr):  Returns the value associated with the name passed in attr. Returns null if attr is not found.

Enumeration getAttributeNames( ):  Returns an enumeration of the attribute names associated with the session.

long getCreationTime( ):  Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when this session was created.

String getId( ):  Returns the session ID.

long getLastAccessedTime( ):  Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the client last made a request for this session.

void invalidate( ):  Invalidates this session and removes it from the context.

boolean isNew( ):  Returns true if the server created the session and it has not yet been accessed by the client.

void removeAttribute(String attr):  Removes the attribute specified by attr from the session.

void setAttribute(String attr, Object val):  Associates the value passed in val with the attribute name passed in attr.

The HttpSessionBindingListener Interface
The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. The methods that are invoked when an object is bound or unbound are

      void valueBound(HttpSessionBindingEvent e)
      void valueUnbound(HttpSessionBindingEvent e)

Here, e is the event object that describes the binding.

The Cookie Class
The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online store. A cookie can save the user’s name, address, and other information. The user does not need to enter this data each time he or she visits the store. A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser.

The names and values of cookies are stored on the user’s machine. Some of the information that is saved for each cookie includes the following:
  • The name of the cookie
  • The value of the cookie
  • The expiration date of the cookie
  • The domain and path of the cookie

The expiration date determines when this cookie is deleted from the user’s machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the user’s machine. The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it is not. There is one constructor for Cookie. It has the signature shown here:

      Cookie(String name, String value)

Here, the name and value of the cookie are supplied as arguments to the constructor.

The Methods Defined by Cookie

Object clone( ):  Returns a copy of this object.

String getComment( ):  Returns the comment.

String getDomain( ):  Returns the domain.

int getMaxAge( ):  Returns the age (in seconds).

String getName( ):  Returns the name.

String getPath( ):  Returns the path.

boolean getSecure( ):  Returns true if the cookie must be sent using only a secure protocol. Otherwise, returns false.

String getValue( ):  Returns the value.

int getVersion( ):  Returns the cookie protocol version. (Will be 0 or 1.)

void setComment(String c):  Sets the comment to c.

void setDomain(String d):  Sets the domain to d.

void setMaxAge(int secs):  Sets the maximum age of the cookie to secs. This is the number of seconds after which the cookie is deleted. Passing –1 causes the cookie to be removed when the browser is terminated.

void setPath(String p):  Sets the path to p.

void setSecure(boolean secure):  Sets the security flag to secure, which means that cookies will be sent only when a secure protocol is being used.

void setValue(String v):  Sets the value to v.

void setVersion(int v):  Sets the cookie protocol version to v, which will be 0 or 1.


The HttpServlet Class
The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests. 

The Methods Defined by HttpServlet

void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Performs an HTTP DELETE.

void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Performs an HTTP GET.

void doHead(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Performs an HTTP HEAD.

void doOptions(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Performs an HTTP OPTIONS.

void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Performs an HTTP POST.

void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Performs an HTTP PUT.

void doTrace(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Performs an HTTP TRACE.

long getLastModified(HttpServletRequest req):  Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the requested resource was last modified.

void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException:  Called by the server when an HTTP request arrives for this servlet. The arguments provide access to the HTTP request and response, respectively.

The HttpSessionEvent Class
HttpSessionEvent encapsulates session events. It extents EventObject and is generated when a change occurs to the session. It defines this constructor:

      HttpSessionEvent(HttpSession session)

Here, session is the source of the event.

HttpSessionEvent defines one method, getSession( ), which is shown here:

      HttpSession getSession( )

It returns the session in which the event occurred.

The HttpSessionBindingEvent Class
The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is bound to or unbound from a value in an HttpSession object. It is also generated when an attribute is bound or unbound. Here are its constructors:

      HttpSessionBindingEvent(HttpSession session, String name)
      HttpSessionBindingEvent(HttpSession session, String name, Object val)

Here, session is the source of the event and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in val. The getName ( ) method obtains the name that is being bound or unbound. Its is shown here:

      String getName( )

The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound:

      HttpSession getSession( )

The getValue( ) method obtains the value of the attribute that is being bound or unbound. It is shown here:

      Object getValue( )

No comments:

Post a Comment