Servlet form data


In many cases, some information needs to be passed from the browser to the web server and finally to the background program. The browser uses 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 to the page request. The page and the encoded information are separated by ? characters, as shown below:

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

The GET method is the default method of transmitting information from the browser to the Web server. It will produce a very long string, which appears. in the browser's address bar. If you are passing passwords or other sensitive information to the server, do not use the GET method. The GET method has a size limit: you can only have a maximum of 1024 characters in the request string.

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

POST method

Another more reliable method of transmitting information to the background 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 the information as a separate message. Messages are passed to the background program as standard output, which you can parse and use. Servlets use the doPost() method to handle this type of request.

Use Servlet to read form data

Servlet processes form data, which will be automatically parsed using different methods according to different situations:

  • getParameter(): You can call the request.getParameter() method to get the value of a form parameter.

  • getParameterValues(): If the parameter appears more than once, this method is called and multiple values ​​are returned, such as a checkbox.

  • getParameterNames(): Call this method if you want to get a complete list of all parameters in the current request.

Example using the GET method of URL

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

http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI

The following is the processing of Web browser inputHelloForm.java Servlet program. We will use the getParameter() method to easily access the passed information:

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 {
		// 设置响应内容类型
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();
		String title = "使用 GET 方法读取表单数据";
		String docType =
		"<!doctype html public \"-//w3c//dtd html 4.0 " +
		"transitional//en\">\n";
		out.println(docType +
		    "<html>\n" +
		    "<head><title>" + title + "</title></head>\n" +
		    "<body bgcolor=\"#f0f0f0\">\n" +
		    "<h1 align=\"center\">" + title + "</h1>\n" +
		    "<ul>\n" +
		    "  <li><b>名字</b>:"
		    + request.getParameter("first_name") + "\n" +
		    "  <li><b>姓氏</b>:"
		    + request.getParameter("last_name") + "\n" +
		    "</ul>\n" +
		    "</body></html>");
	}

}

Assuming your environment has been set up correctly, compile HelloForm.java as follows:

$ javac HelloForm.java

If all goes well, the above compilation will produce the HelloForm.class file. Next, you must copy the class file to <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes and locate it in <Tomcat-installation-directory>/webapps/ROOT/WEB- Create the following entry in the web.xml file of INF/:

    <servlet>
        <servlet-name>HelloForm</servlet-name>
        <servlet-class>HelloForm</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloForm</servlet-name>
        <url-pattern>/HelloForm</url-pattern>
    </servlet-mapping>

Now enter http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in the address bar of the browser and make sure that the Tomcat server has been started before triggering the above command. If all goes well, you will get the following results:

Using the GET method to read the form data

  • First name: ZARA

  • Last name: ALI

##Using the form's GET method example

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.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<form action="HelloForm" method="GET">
名字:<input type="text" name="first_name">
<br />
姓氏:<input type="text" name="last_name" />
<input type="submit" value="提交" />
</form>
</body>
</html>

Save this HTML to the hello.htm file and place it in the <Tomcat-installation-directory>/webapps/ROOT directory. Below is the actual output of the above form when you visit

http://localhost:8080/Hello.htm.

Try entering your first and last name, then click the "Submit" button to view the output on your local machine. Based on the input provided, it produces similar results to the previous instance.

Using the form's POST method example

Let's make a small modification to the above Servlet so that it can handle both GET and POST methods. The following

HelloForm.java Servlet program uses the GET and POST methods to process input given by a web browser.

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// 扩展 HttpServlet 类
public class HelloForm extends HttpServlet {
 
  // 处理 GET 方法请求的方法
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");

      PrintWriter out = response.getWriter();
	  String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>名字</b>:"
                + request.getParameter("first_name") + "\n" +
                "  <li><b>姓氏</b>:"
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // 处理 POST 方法请求的方法
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

Now, compile and deploy the above Servlet, and use Hello.htm with the POST method to test, as shown below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<form action="HelloForm" method="POST">
名字:<input type="text" name="first_name">
<br />
姓氏:<input type="text" name="last_name" />
<input type="submit" value="提交" />
</form>
</body>
</html>

The following is the actual output of the above form, try to enter the name and last name, then click the "Submit" button to view the output on your local computer.

Based on the input provided, it will produce similar results to the previous instance.

Transfer the check box data to the Servlet program

When you need to select more than one option, use the check box.

The following is an HTML code example CheckBox.htm, a form with two check boxes.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> 数学
<input type="checkbox" name="physics"  /> 物理
<input type="checkbox" name="chemistry" checked="checked" /> 
                                                化学
<input type="submit" value="选择学科" />
</form>
</body>
</html>

The result of this code is the following form:

The following is the CheckBox.java Servlet program that handles the check box input given by the web browser.

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// 扩展 HttpServlet 类
public class CheckBox extends HttpServlet {
 
  // 处理 GET 方法请求的方法
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");

      PrintWriter out = response.getWriter();
	  String title = "读取复选框数据";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>数学标识:</b>: "
                + request.getParameter("maths") + "\n" +
                "  <li><b>物理标识:</b>: "
                + request.getParameter("physics") + "\n" +
                "  <li><b>化学标识:</b>: "
                + request.getParameter("chemistry") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
  // 处理 POST 方法请求的方法
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

The above example will display the following results:

Read all form parameters

The following is a general example, use the getParameterNames() method of HttpServletRequest to read all available form parameters. This method returns an enumeration containing parameter names in unspecified order.

Once we have an enum, we can loop through the enum in the standard way, using the hasMoreElements() method to determine when to stop, using 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 {
		// 设置响应内容类型
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String title = "读取所有的表单数据";
		String docType =
			"<!doctype html public \"-//w3c//dtd html 4.0 " +
			"transitional//en\">\n";
			out.println(docType +
			"<html>\n" +
			"<head><meta charset=\"utf-8\"><title>" + title + "</title></head>\n" +
			"<body bgcolor=\"#f0f0f0\">\n" +
			"<h1 align=\"center\">" + title + "</h1>\n" +
			"<table width=\"100%\" border=\"1\" align=\"center\">\n" +
			"<tr bgcolor=\"#949494\">\n" +
			"<th>参数名称</th><th>参数值</th>\n"+
			"</tr>\n");

		Enumeration paramNames = request.getParameterNames();

		while(paramNames.hasMoreElements()) {
			String paramName = (String)paramNames.nextElement();
			out.print("<tr><td>" + paramName + "</td>\n");
			String[] paramValues =
			request.getParameterValues(paramName);
			// 读取单个值的数据
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() == 0)
					out.println("<td><i>没有值</i></td>");
				else
					out.println("<td>" + paramValue + "</td>");
			} else {
				// 读取多个值的数据
				out.println("<td><ul>");
				for(int i=0; i < paramValues.length; i++) {
				out.println("<li>" + paramValues[i]);
			}
				out.println("</ul></td>");
			}
			out.print("</tr>");
		}
		out.println("\n</table>\n</body></html>");
	}

	/**
	 * @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 through the form below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> 数学
<input type="checkbox" name="physics"  /> 物理
<input type="checkbox" name="chemistry" checked="checked" /> 化学
<input type="submit" value="选择学科" />
</form>

</body>
</html>

Now call the Servlet using the above form, which will produce the following results:

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

Read checkbox data

  • Mathematical identification: on

  • Physical identification: null

  • Chemistry Identification: on