Servlet: Get front-end data; Servlet: Get Data
Java provides the following methods to obtain the get or post data of a webpage:
- GetParameter (name); method for obtaining a single parameter.
- GetParameterValues (name); method for obtaining multiple parameter values, such as the value of the check box, returns an array
- GetParameterNames (name); obtain all parameters in the request and return an enumeration type.
This instance is mainly about getParameter () and getParameterValues.
Instance:
HTML:
1 <! DOCTYPE html> 2 <! -- For simplicity, don't write comments --> 3
Servlet code: servlet/Test. java:
1 package servlet; 2 3 import java. io. IOException; 4 import java. io. printWriter; 5 import java. text. simpleDateFormat; 6 import java. util. date; 7 8 import javax. servlet. servletException; 9 import javax. servlet. http. httpServlet; 10 import javax. servlet. http. httpServletRequest; 11 import javax. servlet. http. httpServletResponse; 12 13 14 15 public class Test extends HttpServlet {// method for implementing doGet in HttpServlet 44 public void doGet (HttpServletRequest request, HttpServletResponse response) 45 throws ServletException, IOException {// get method is similar to post, and garbled problem is difficult to solve 54 55} 56 // implement the doPost method 67 public void doPost in HttpServlet (HttpServletRequest request, HttpServletResponse response) 68 throws ServletException, IOException {69 // fix Chinese garbled characters in Post 70 request. setCharacterEncoding ("UTF-8"); 71 73 String username, mypassword; 74 String [] favorite; PrintWriter out = response. getWriter (); 76 77 78 try 79 {
// Get the single parameter value 80 username = request. getParameter ("username") through getParameter ");
// Output 81 System. out. println ("Post method username =" + username) to the background; 82 out. println ("name:" + usrname );
// Use the getParameterValues method to obtain the value of the check box 83 favorite = request. getParameterValues ("holobby"); out. println ("Hobbies:" + favorite); 99} 100 catch (Exception ex) 101 {102 ex. printStackTrace (); 103} 104 105 106} 118}
In Servlet code, rows 80th and 83 are used by getParameter () and getParameterValues.
There is no get write method here. First, it is necessary to solve Chinese garbled characters. Second, it is the same as the post method, so I will not write more. Just grasp the idea. getParameterNames () is not very common and I will not write it.