Latest web development tutorials

Servlet form data

In many cases, we need to pass some information from the browser to the Web server, and ultimately to the daemon. Browsers are two ways to pass information to the Web server are GET and POST methods.

GET Method

GET method to send the user information encoded to the page request. Page and intermediate information encoded using character-delimited, as follows?:

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

GET is the default method of passing information from the browser to the Web server process which will produce a long string, it appears in the browser's address bar. If you want to pass a server passwords or other sensitive information, please do not use the GET method. There GET method size limit: request string can have up to 1024 characters.

This information is transmitted using QUERY_STRING head, and can be accessed through the QUERY_STRING environment variable, Servlet usedoGet () method to handle this type of request.

POST method

Another more reliable method of passing information to the daemon is POST method. POST method to package information in essentially the same manner as GET, POST method but not the information as a URL? Text string after the character is transmitted, but the information as a separate message. Message in the form of standard output reached daemon, you can parse and use them to standard output. Use Servlet doPost () method to handle this type of request.

Use Servlet to read form data

Servlet to process the form data, which use different methods depending on the situation automatically resolve:

  • getParameter (): You can call request.getParameter () method to get the value of the form parameter.
  • getParameterValues (): If the parameter appears more than once, then call the method and return multiple values, such as check boxes.
  • getParameterNames (): If you want to get a complete list of current requests all the parameters, then call the method.

Examples of use of the URL GET method

Here is a simple URL, using GET method to pass two values ​​to HelloForm program.

http: // localhost: 8080 / TomcatTest / HelloForm name = This tutorial & url = www.w3big.com?

Here is the deal with Web browser enteredHelloForm.java Servlet program.We will use thegetParameter () method, you can easily access information transmission:

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

		PrintWriter out = response.getWriter();
		String title = "使用 GET 方法读取表单数据";
		// 处理中文
		String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
		String docType = "<!DOCTYPE html> \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>:"
		    + name + "\n" +
		    "  <li><b>网址</b>:"
		    + request.getParameter("url") + "\n" +
		    "</ul>\n" +
		    "</body></html>");
	}
	
	// 处理 POST 方法请求的方法
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
We then create the following entry in theweb.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>HelloForm</servlet-name>
    <servlet-class>com.w3big.test.HelloForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <url-pattern>/TomcatTest/HelloForm</url-pattern>
  </servlet-mapping>
</web-app>

Now enter in the browser address barhttp: // localhost: 8080 / TomcatTest/ HelloForm name =This tutorial & url = www.w3big.com,and before triggering the above command has been launched to ensure the Tomcatserver?.If all goes well, you will get the following results:


Use the form GET method of Example

Here is a simple example, using HTML forms and submit button passes the two values. We will use the same Servlet HelloForm to process the input.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>
<form action="HelloForm" method="GET">
网址名:<input type="text" name="name">
<br />
网址:<input type="text" name="url" />
<input type="submit" value="提交" />
</form>
</body>
</html>

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

Try entering the URL name and URL, and click "Submit" button, Gif demo as follows:


Examples of the form's POST method

Let us do a little above Servlet modified so that it can handle GET and POST methods. The followingHelloForm.java Servlet uses the GET and POST method for processing the input given by the Web browser.

Note: If the data submitted form data in Chinese transcoding is required:

String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
package com.w3big.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 {
		// 设置响应内容类型
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();
		String title = "使用 POST 方法读取表单数据";
		// 处理中文
		String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
		String docType = "<!DOCTYPE html> \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>:"
		    + name + "\n" +
		    "  <li><b>网址</b>:"
		    + request.getParameter("url") + "\n" +
		    "</ul>\n" +
		    "</body></html>");
	}
	
	// 处理 POST 方法请求的方法
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Now, compile the deployment of the above Servlet, and use hello.html with POST methods were tested, as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>
<form action="HelloForm" method="POST">
网址名:<input type="text" name="name">
<br />
网址:<input type="text" name="url" />
<input type="submit" value="提交" />
</form>
</body>
</html>

Here is the actual output form above, try to enter the URL name and URL, and click "Submit" button, Gif demo as follows:


To pass data to the Servlet box program

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

Here is an HTML code examples checkbox.html, a form with two checkboxes.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="w3big" checked="checked" /> 本教程
<input type="checkbox" name="google"  /> Google
<input type="checkbox" name="taobao" checked="checked" /> 淘宝
<input type="submit" value="选择站点" />
</form>
</body>
</html>

Here is CheckBox.java Servlet procedures for handling Web browser gives input box.

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

		PrintWriter out = response.getWriter();
		String title = "读取复选框数据";
		String docType = "<!DOCTYPE html> \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("w3big") + "\n" +
	            "  <li><b>Google 标识:</b>: "
	            + request.getParameter("google") + "\n" +
	            "  <li><b>淘宝标识:</b>: "
	            + request.getParameter("taobao") + "\n" +
	            "</ul>\n" +
	            "</body></html>");
	}
	
	// 处理 POST 方法请求的方法
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Set the corresponding web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>CheckBox</servlet-name>
    <servlet-class>com.w3big.test.CheckBox</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CheckBox</servlet-name>
    <url-pattern>/TomcatTest/CheckBox</url-pattern>
  </servlet-mapping>
</web-app>

The above example will show the following results:


Read all of the parameters of the form

The following is a generic example of the use of HttpServletRequestgetParameterNames () method to read all the available parameters of the form.This method returns an enumeration containing the parameter name is not specified order.

Once we have an enumeration, we can enumerate circulating in a standard manner, usinghasMoreElements ()method to determine when to stop usingnextElement ()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>本教程(w3big.com)</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>

Set the corresponding web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>ReadParams</servlet-name>
    <servlet-class>com.w3big.test.ReadParams</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ReadParams</servlet-name>
    <url-pattern>/TomcatTest/ReadParams</url-pattern>
  </servlet-mapping>
</web-app>

Now use the form above to call Servlet, produces the following results:

You can try to read the other above Servlet form data, such as text boxes, radio buttons, or drop-down box and so on.