Java Servlet Request & Response Interfaces

Details about Request & Response interfaces.

  • HttpServlet gets request from a client (browser) on the HttpServletRequest interface and can return response to the client through the HttpServletResponse interface in all the doXXXX methods.
  • Here is some of most used HttpServletRequest Methods:

    Method Description
    public Enumeration getParameterNames() Names of the parameters contained in this request.
    public String[] getParameterValues(String name) Used when the named parameter may have multiple values.
    public Map getParameterMap() Returns all the parameters stored in a Map object.
    public BufferedReader getReader() This will retrieve the body of a request as characters into a BufferedReader.
    public ServletInputStream getInputStream() This will retrieve the body of a request as binary data into a ServletInputStream.
    public Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains.
    public String getQueryString() This will return the query string that is contained in the request URL after the path.
    public RequestDispatcher getRequestDispatcher(String path) A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response.
  • You have to use either the getReader() method or the getInputStream(). You cannot combine to use these for the same request.
  • Here is some of most used HttpServletResponse Methods:

    Method Description
    public PrintWriter getWriter() This will return a PrintWriter object that can send character text to the client.
    public ServletOutputStream getOutputStream() This will return a ServletOutputStream suitable for writing binary data in the response.
    public addHeader(String name, String value) This will add a property, which is a String name with a String value to the response header.
    public addDateHeader(String name, long date) This will add a property, which is a String name with a long date value to the response header.
    public void sendRedirect(String location) This will send a temporary redirect response to the client using the specified redirect location URL.
    public Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains.

  • You have to use either the getWriter() method or the getOutputStream(). You cannot combine to use these for the same response

Example of Servlet handling a html form input.

As selected we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletFormhandling).

  • Simple servlet handling a html form input example:
    package app.form;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class FormHandlerServlet extends HttpServlet
    {
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
      {
        String enteredValue;
        // gets all the selected options from the client browser
        String[] selectedOptions = request.getParameterValues("options");
        // gets the enteredValue fields value
        enteredValue = request.getParameter("enteredValue");
        response.setContentType("text/html");
        PrintWriter printWriter;
        try
        {
          // get a printwriter from the HttpServletResponse objects ref.
          printWriter = response.getWriter();
          // return on the HttpServletResponse objects ref. requested values
          printWriter.println("<p>");
          printWriter.print("You entered: ");
          printWriter.print(enteredValue);
          printWriter.print("</p>");
          printWriter.println("<p>");
          printWriter.print("The following options were selected:");
          printWriter.println("<br/>");
    
          if (selectedOptions != null)
          {
            for (String option : selectedOptions)
            {
              printWriter.print(option);
              printWriter.println("<br/>");
            }
          }
          else
          {
            printWriter.println("None");
          }
          printWriter.println("</p>");
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is FormHandlerServlet).

  • In this servlet we expect a POST Http request and we fetch all the values we know about from a html form (read the comments).
  • We set the Content type to "text/html" for the response to the client (browser) and use a PrintWriter on the response object to return html codes and text back to the client.
    We need a html startup file, dataentry.html, for the browser like this:
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="windows-1252">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Data Entry Page</title>
      </head>
      <body>
        <form method="post" action="FormHandlerServlet" 
              style="width: 310px; border: 1px solid black;" >
          <table >
            <tr>
              <td>Please enter some text:</td>
              <td><input type="text" name="enteredValue" />          
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <input name="options" type="checkbox"  value="option1" />
                Option 1</td>
            </tr>
            <tr>
              <td colspan="2">
                <input name="options" type="checkbox" value="option2" />
                Option 2</td>
            </tr>
            <tr>
              <td colspan="2">
                <input name="options" type="checkbox" value="option3" />
                Option 3</td>
            </tr>
            <tr>
              <td colspan="2" style="text-align: right;" >
                <input type="submit" value="Submit">
              </td>
            </tr>
          </table>
        </form>
      </body>
    </html>

    For those who participate in the review: create a HTML page in Netbeans and replace generated code for the html file with that shown above (the name of the html should be dataentry and places in the folder web).

Creating Deployment descriptor.

  • To run this Servlet you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml. In the later version of java it is possible to specify this in the form of annotations in front of the Servlet.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file regarding servlet, FormHandlerServlet, should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
      <servlet>
        <servlet-name>FormHandlerServlet</servlet-name>
        <servlet-class>app.form.FormHandlerServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>FormHandlerServlet</servlet-name>
        <url-pattern>/FormHandlerServlet</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>dataentry.html</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a Servlet.
  • With a servlet tag we give the Servlet class a servlet name, which is used in the servlet-mapping tag to specify a url for the Servlet.
  • In this way we can have many urls for the same servlet.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file dataentry.html. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ServletFormhandling) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a Glassfish deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/ServletFormhandling</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:
    Please enter some text:
    Option 1
    Option 2
    Option 3

    Enter a text, select some options and press the submit button.

    The result back to the browser from the Servlet should be something like:
    You entered: I am 40 years old

    The following options were selected:
    option1
    option2
Prev. in menu Servlet/Request.php Next in menu
Prev. in menu Servlet/Request.php Next in menu
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.