English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In many cases, it is necessary to pass some information from the browser to the web server and finally to the backend program. Browsers use two methods to pass this information to the web server, namely GET method and POST method.
The GET method sends encoded user information to 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 transmitting information from the browser to the web server, which generates a very long string that appears in the browser's address bar. If you need to pass passwords or other sensitive information to the server, do not use the GET method. The GET method has size limits: there can be at most 1024 characters.
These information are passed using the QUERY_STRING header and can be accessed through the QUERY_STRING environment variable, Servlet uses doGet() method to handle this type of request.
Another more reliable method to pass information to the backend program is the POST method. The POST method packages information in a way similar to the GET method, but instead of sending the information as a text string after the ? character in the URL, it sends these information as a separate message. The message is transmitted to the backend program in the form of standard output, and you can parse and use these standard outputs. Servlets use the doPost() method to handle this type of request.
Servlet processes form data, which is automatically parsed using different methods depending on the situation:
getParameter():You can call the request.getParameter() method to get the value of the form parameter.
getParameterValues():If the parameter appears more than once, call this method and return multiple values, such as checkboxes.
getParameterNames():If you want to get a complete list of all parameters in the current request, call this method.
下面是一个简单的 URL,将使用 GET 方法向 HelloForm 程序传递两个值。
http://localhost:8080/TomcatTest/HelloForm?name=Basic Tutorial Website&url=www.oldtoolbag.com
Below is a simple URL that will use the GET method to pass two values to the HelloForm program. HelloForm.java Below is the code to handle input from the web browser Servlet program. We will use methods, you can easily access the information passed: getParameter()
package com.w3codebox.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 = "Using GET method to read form data"; // Handle Chinese String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8")-8859-1),"UTF-8"-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>Website Name</b>" + name + "\n" + "<li><b>Website</b>" + request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>"); } // A method to handle POST method requests public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Then we in web.xml Create the following entry in the file
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>HelloForm</servlet-name> <servlet-class>com.w3codebox.test.HelloForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloForm</servlet-name> <url-pattern>/TomcatTest/HelloForm</url-pattern> </servlet-mapping> </web-app>
Now enter the following simple URL in the browser's address bar http://localhost:8080/TomcatTest/HelloForm?name=Basic Tutorial Website&url=www.oldtoolbag.com , and make sure that the Tomcat server is running before triggering the above command. If everything goes well, you will get the following result:
Below is a simple example using an HTML form and a submit button to pass two values. We will use the same Servlet HelloForm to process the input.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>基础教程网(oldtoolbag.com)</title> </head> <body> <form action="HelloForm" method="GET"> Website Name: <input type="text" name="name"> <br> /> Website: <input type="text" name="url" /> <input type="submit" value="Submit" /> </form> </body> </html>
Save this HTML to the hello.html file, with the directory structure as shown below:
Try entering the website name and URL, then click the "Submit" button. The demonstration is as follows:
Let's make a small modification to the above Servlet so that it can handle GET and POST methods. Below HelloForm.java The Servlet program uses GET and POST methods to process input from the web browser.
Note: If there is Chinese data in the form submission data, it needs to be encoded:
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8")8859-1),"UTF-8"-8");
package com.w3codebox.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 = "Using POST method to read form data"; // Handle Chinese String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8")8859-1),"UTF-8"-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>Website Name</b>" + name + "\n" + "<li><b>Website</b>" + request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>"); } // A method to handle POST method 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 the hello.html with the POST method as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>基础教程网(oldtoolbag.com)</title> </head> <body> <form action="HelloForm" method="POST"> Website Name: <input type="text" name="name"> <br> /> Website: <input type="text" name="url" /> <input type="submit" value="Submit" /> </form> </body> </html>
Below is the actual output of the above form. Try entering the website name and URL, then click the "Submit" button. The demonstration is as follows:
Use checkboxes when you need to select more than one option.
Below is an HTML code example checkbox.html, a form with two checkboxes.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>基础教程网(oldtoolbag.com)</title> </head> <body> <form action="CheckBox" method="POST" target="_blank"> <input type="checkbox" name="w"3codebox" checked="checked" /> Basic Tutorial Website <input type="checkbox" name="google" /> Google <input type="checkbox" name="taobao" checked="checked" /> Taobao <input type="submit" value="Select site" /> </form> </body> </html>
Below is the CheckBox.java Servlet program, which processes the checkbox input provided by the web browser.
package com.w3codebox.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 = "Read checkbox data"; 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>Knack tutorial identifier:</b>/b>: " + request.getParameter("w")3codebox()) + "\n" + " <li><b>Google identifier:</b>/b>: " + request.getParameter("google") + "\n" + " <li><b>Taobao Identifier:</b>: " + request.getParameter("taobao") + "\n" + "</ul>\n" + "</body></html>"); } // A method to handle POST method requests 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.w3codebox.test.CheckBox</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckBox</servlet-name> <url-pattern>/TomcatTest/CheckBox</url-pattern> </servlet-mapping> </web-app>
The URL accessed in the above example: http://localhost:8080/TomcatTest/checkbox.html to view the output results.
Here is a general example using HttpServletRequest's getParameterNames() A method to read all available form parameters. This method returns an enumeration containing parameter names in an unspecified order.
Once we have an enumeration, we can iterate through the enumeration in a standard way, using hasMoreElements() A method to determine when to stop, using nextElement() A method to obtain 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 = "Read all form data"; 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>Parameter Name</th><th>Parameter Value</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); // reading single value data if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println("<td><i>No value</i></td>"); else out.println("<td>" + paramValue + "</td>"); } else { // reading multiple values data 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 following form:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>基础教程网(oldtoolbag.com)</title> </head> <body> <form action="ReadParams" method="POST" target="_blank"> <input type="checkbox" name="maths" checked="checked"> /Mathematics <input type="checkbox" name="physics"> /Physics <input type="checkbox" name="chemistry" checked="checked"> /Chemistry <input type="submit" value="Select Subject"> /> </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.w3codebox.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 above form to call Servlet, access address: http://localhost:8080/TomcatTest/test.html View Output Results.
You can try using the above Servlet to read other form data, such as text boxes, radio buttons, or drop-down boxes, etc.