Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Servlet Form Data

Servlet Form Data

In many cases, some information needs to be passed from the browser to the Web server and ultimately to the back-end program. Browsers use two methods to pass this information to the Web server: the GET method and the POST method.

GET Method

The GET method sends encoded user information as part of the page request. The page and the encoded information are separated by the ? character, as shown below:



http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default method for passing information from the browser to the Web server. It produces a very long string that appears in the browser's address bar. If you are passing a password or other sensitive information to the server, do not use the GET method. The GET method has a size limit: a request string can contain at most 1024 characters.

This information is passed using the QUERY_STRING header and can be accessed through the QUERY_STRING environment variable. Servlets use the doGet() method to handle this type of request.

POST Method

Another more reliable method of passing information to the back-end program is the POST method. The POST method packages information in much the same way as the GET method, but instead of sending the information as a text string after the ? character in the URL, the POST method sends it as a separate message. The message is passed to the back-end program as standard output, which you can parse and use. Servlets use the doPost() method to handle this type of request.

Reading Form Data with a Servlet

Servlets process form data, which is automatically parsed using different methods depending on the situation:

Example of Using the GET Method with a URL

The following is a simple URL that uses the GET method to pass two values to the HelloForm program.

http://localhost:8080/TomcatTest/HelloForm?name=Runoob Tutorial&url=www.runoob.com

The following is the HelloForm.java Servlet program that handles input from the Web browser. We will use the getParameter() method, which makes it easy to access the information passed:



package com.runoob.test;



import java.io.IOException;

import java.io.PrintWriter;



import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



/**

 * Servlet implementation class HelloForm

 */

@WebServlet("/HelloForm")

public class HelloForm extends HttpServlet {

    private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public HelloForm() {

        super();

        // TODO Auto-generated constructor stub

    }



    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Set response content type

        response.setContentType("text/html;charset=UTF-8");



        PrintWriter out = response.getWriter();

        String title = "Reading Form Data Using the GET Method";

        // Process Chinese

        String name =new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");

        String docType = " \n";

        out.println(docType +

            "\n" +

            "" + title + "\n" +

            "\n" +

            "

" + title + "

\n" +          "
    \n" +          "
  • 站点名:"          + name + "\n" +          "
  • 网址:"          + request.getParameter("url") + "\n" +          "
\n" +          "");     }          // Method to handle POST requests     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         doGet(request, response);     } }

Then we

web.xml

create the following entry:







  

    HelloForm

    com.runoob.test.HelloForm

  

  

    HelloForm

    /TomcatTest/HelloForm

  



Now enter http://localhost:8080/TomcatTest/HelloForm?name=Runoob Tutorial&url=www.runoob.com in the browser's address bar, and make sure the Tomcat server has been started before triggering the above command. If all goes well, you will get the following result:


Example of Using the GET Method with a Form

The following is a simple example that uses an HTML form and a submit button to pass two values. We will use the same Servlet, HelloForm, to handle the input.











Runoob Tutorial(runoob.com)





网址名:
网址:

Save this HTML to the hello.html file. The directory structure is as follows:

Try entering a website name and URL, then click the "Submit" button. The GIF demonstration is as follows:


Example of Using the POST Method with a Form

Let's make a small modification to the Servlet above so that it can handle both GET and POST methods. The following HelloForm.java Servlet program uses both GET and POST methods to handle input given by the Web browser.

Note: if the data submitted by the form contains Chinese characters, transcoding is required:

String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");



package com.runoob.test;



import java.io.IOException;

import java.io.PrintWriter;



import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



/**

 * Servlet implementation class HelloForm

 */

@WebServlet("/HelloForm")

public class HelloForm extends HttpServlet {

    private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public HelloForm() {

        super();

        // TODO Auto-generated constructor stub

    }



    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Set response content type

        response.setContentType("text/html;charset=UTF-8");



        PrintWriter out = response.getWriter();

        String title = "Reading Form Data Using the POST Method";

        // Process Chinese

        String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");

        String docType = " \n";

        out.println(docType +

            "\n" +

            "" + title + "\n" +

            "\n" +

            "

" + title + "

\n" +          "
    \n" +          "
  • 站点名:"          + name + "\n" +          "
  • 网址:"          + request.getParameter("url") + "\n" +          "
\n" +          "");     }          // Method to handle POST requests     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         doGet(request, response);     } }

Now, compile and deploy the above Servlet, and test it using hello.html with the POST method, as shown below:











Runoob Tutorial(runoob.com)





网址名:
网址:

The following is the actual output of the form above. Try entering a website name and URL, then click the "Submit" button. The GIF demonstration is as follows:


Passing Checkbox Data to a Servlet Program

Checkboxes are used when more than one option needs to be selected.

The following is an HTML code example, checkbox.html, a form with two checkboxes.











Runoob Tutorial(runoob.com)





Runoob Tutorial Google 淘宝

The following is the CheckBox.java Servlet program, which handles checkbox input given by the Web browser.



package com.runoob.test;



import java.io.IOException;

import java.io.PrintWriter;



import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



/**

 * Servlet implementation class CheckBox

 */

@WebServlet("/CheckBox")

public class CheckBox extends HttpServlet {

    private static final long serialVersionUID = 1L;

    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        

        // Set response content type

        response.setContentType("text/html;charset=UTF-8");



        PrintWriter out = response.getWriter();

        String title = "Reading Checkbox Data";

        String docType = " \n";

            out.println(docType +

                "\n" +

                "" + title + "\n" +

                "\n" +

                "

" + title + "

\n" +      "
    \n" +      "
  • 菜鸟按教程标识:: "      + request.getParameter("runoob") + "\n" +      "
  • Google 标识:: "      + request.getParameter("google") + "\n" +      "
  • 淘宝标识:: "      + request.getParameter("taobao") + "\n" +      "
\n" +      "");     }          // Method to handle POST requests     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         doGet(request, response);     } }

Set the corresponding web.xml:







  

    CheckBox

    com.runoob.test.CheckBox

  

  

    CheckBox

    /TomcatTest/CheckBox

  



The example above will display the following result:


Reading All Form Parameters

The following is a general example that uses the getParameterNames() method of HttpServletRequest to read all available form parameters. This method returns an Enumeration containing the names of the parameters in no particular order.

Once we have an enumeration, we can iterate over it in the standard way, using the hasMoreElements() method to determine when to stop, and the nextElement() method to get the name of each parameter.



import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;



import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



/**

 * Servlet implementation class ReadParams

 */

@WebServlet("/ReadParams")

public class ReadParams extends HttpServlet {

    private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public ReadParams() {

        super();

        // TODO Auto-generated constructor stub

    }



    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Set response content type

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        String title = "Reading All Form Data";

        String docType =

            "\n";

            out.println(docType +

            "\n" +

            "" + title + "\n" +

            "\n" +

            "

" + title + "

\n" +             "\n" +             "\n" +             "\n"+             "\n");         Enumeration paramNames = request.getParameterNames();         while(paramNames.hasMoreElements()) {             String paramName = (String)paramNames.nextElement();             out.print("\n");             String[] paramValues =             request.getParameterValues(paramName);             // Read a single value             if (paramValues.length == 1) {                 String paramValue = paramValues[0];                 if (paramValue.length() == 0)                     out.println("");                 else                     out.println("");             } else {                 // Read multiple values                 out.println("");             }             out.print("");         }         out.println("\n
参数名称参数值
" + paramName + "没有值" + paramValue + "
    ");                 for(int i=0; i < paramValues.length; i++) {                 out.println("
  • " + paramValues[i]);             }                 out.println("
\n");     }     /**      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)      */     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         // TODO Auto-generated method stub         doGet(request, response);     } }

Now, try the above Servlet with the following form:











Runoob Tutorial(runoob.com)







数学 物理 化学

Set the corresponding web.xml:







  

    ReadParams

    com.runoob.test.ReadParams

  

  

    ReadParams

    /TomcatTest/ReadParams

  



Now, invoking the Servlet using the form above will produce the following result:

You can try using the above Servlet to read other form data, such as text boxes, radio buttons, or drop-down lists.