Table of contents
| Request object HttpServletRequest interface
Basic overview of HttpServletRequest
Request object get URL & Method
The request object gets the parameter name
request object get parameter value
Parameter value garbled problem
This article belongs to the third part of the back-end full set of notes
| Request object HttpServletRequest interface
Basic overview of HttpServletRequest
Where is HttpServletRequest used?
-
Careful observation reveals that the parameter lists of the previous doGet and doPost methods are
HttpServletRequest req, HttpServletResponse resp
-
These two parameters are the HttpServletRequest we are learning now and the HttpServletRespose we will learn later
-
Let's review the whole process of Tomcat processing requests so that we can use it more clearly
When a request is sent to Tomcat, it first goes through the Service and then it is handed over to the Connector. The Connector is used to receive the request and encapsulate the received request into Request and Response for specific processing. After the Request and Response are encapsulated, they are handed over to the Servlet in the Container. Processing, the Container returns to the Connector after processing the request, and finally the Connector returns the processing result to the client through the Socket, so that the entire request is processed!
What is HttpServletRequest?
-
HttpServletRequest comes from the Servlet specification and is an interface
-
Its implementation class is provided by the HTTP server (Tomcat)
-
The implementation class object of HttpServletRequest is called the request object
effect?
-
The HttpServletRequest interface is responsible for reading the information in the Http request protocol package when the doGet/doPost method is running
-
Read the [Request Line] information in the Http request protocol package
-
Read the request parameter information stored in the [request header] or [request body] in the Http request protocol package
-
Instead of the browser, apply for a resource file call from the Http server
Request object get URL & Method
grammar
-
Reference: Difference between URL and URI
request.getRequestURI(); //获取请求行的URI
request.getRequestURL(); //获取请求行的URL
request.getMethod(); //获取请求行的method(请求方式)
example
-
The following Servlet implementation class-related web.xml configuration has been configured.
-
The alias of the website deployed in Tomcat is web2. The alias of the Servlet object is web1.、
-
After the configuration is complete and the code is written, start Tomcat and enter the URL http://localhost:8080/web2/web1 to access the Servlet
public class MyServlet extends HttpServlet {
@Override
public void init() throws ServletException {
super.init();
System.out.println("MyServlet对象被创建了");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.doGet(req, resp); 如果你是要彻底覆盖父类的doGet方法,不需要父类提供的功能,就可以删除super.doGet(req,resp);这一句
System.out.println("这是Servlet的doGet方法");
//request.getRequestURI()
System.out.println("获取到请求行的URL:" + req.getRequestURL()); //http://localhost:8080/web2/web1
System.out.println("获取到请求行的URI:" + req.getRequestURI()); ///web2/web1
//request.getMethod()
System.out.println("获取到请求行的method(请求方式):" + req.getMethod()); //?GET
}
}
The request object gets the parameter name
grammar
Use the getParameterNames method to return an Enumeration enumeration class
Enumeration parameters = request.getParameterNames();
while(parameters.hasMoreElements()){
String parameter = (String)parameters.nextElement(); //得到的是Object,所以要强转为String
}
example
-
The following code, web.xml configuration, and Tomcat deployment are exactly the same as the previous section
-
The URL entered this time is: http://localhost:8080/web2/web1?name=Klee&age=12 to simulate the situation with parameters
public class MyServlet extends HttpServlet {
@Override
public void init() throws ServletException {
super.init();
System.out.println("MyServlet对象被创建了");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//...
//request.getParameters
Enumeration parameters = req.getParameterNames();
while(parameters.hasMoreElements()){
System.out.println("参数名:" + (String)parameters.nextElement());//得到的是Object,所以要强转为String
//参数名:name 参数名:age
}
}
}
request object get parameter value
grammar
String value = request.getParameter(参数名);
Contact the code in the previous section to obtain the parameter name, the complete code is as follows
Enumeration parameters = request.getParameterNames();
int i = 1;
while(parameters.hasMoreElements()){
String parameterName = (String)parameters.nextElement();//得到的是Object,所以要强转为String
String parameterValue = request.getParameter(parameterName);
System.out.println("参数" + i + ":" + parameterName + " = " + parameterValue);
//name = Klee age = 12
}
example
-
The following code, web.xml configuration, and Tomcat deployment are exactly the same as the previous section
-
The URL entered this time is: http://localhost:8080/web2/web1?name=Klee&age=12 to simulate the situation with parameters
public class MyServlet extends HttpServlet {
@Override
public void init() throws ServletException {
super.init();
System.out.println("MyServlet对象被创建了");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//...
//request.getParameters
Enumeration parameters = req.getParameterNames();
int i = 1;
while(parameters.hasMoreElements()){
String parameterName = (String)parameters.nextElement();//得到的是Object,所以要强转为String
String parameterValue = req.getParameter(parameterName);
System.out.println("参数" + i++ + ":" + parameterName + " = " + parameterValue);
//参数1:name = Klee 参数2:age = 12
}
}
}
Parameter value garbled problem
Why are the parameter values obtained from the POST request garbled?
-
If the browser sends a request in GET mode, the request parameters are stored in [Request Header ]. After the Http request protocol packet arrives at the Http server, the first thing to do is to decode the binary content of the request header, which is decoded by Tomcat. Tomcat9.0 uses [by default] utf-8] Character set decoding request header , which can explain all national characters
-
If the browser sends a request in POST mode, the request parameters are stored in the [request body] . After the Http request protocol packet arrives at the Http server, the first thing to do is to decode the binary content of the request body and the current request object (request) is responsible for decoding it. request uses the [IS0-8859-1] character set to decode the request body by default . If an Eastern European character set is used, if the content of the request body parameter is Chinese, it will not be able to decode and only get garbled characters.
-
It should be noted that any version of Tomcat has the problem of garbled POST requests, and only Tomcat before version 8.0 has garbled GET requests (so this section does not introduce garbled GET requests, you need Baidu yourself)
In addition, in addition to the above-mentioned garbled characters caused by the mismatch between the encoding between the Tomcat server and the browser , we also need to consider the garbled characters caused by the encoding settings output by the console , and also consider the garbled characters caused by the local code file. Garbled characters caused by character settings .
If the browser sends a request in POST mode, the request parameters are stored in the [request body] . After the Http request protocol packet arrives at the Http server, the first thing to do is to decode the binary content of the request body and the current request object (request) is responsible for decoding it. request uses the [IS0-8859-1] character set to decode the request body by default . If an Eastern European character set is used, if the content of the request body parameter is Chinese, it will not be able to decode and only get garbled characters.
The basic idea of solving POST garbled characters
In the Post request mode, before reading the content of the request body, the request object should be notified to use the utf-8 character set to re-decode the content of the request body
Solution to POST garbled characters, console output garbled characters, and local code Chinese garbled characters
-
Add code in the first line of the doPost method
req.setCharacterEncoding("UTF-8");
(this method is only valid for POST garbled characters, that is, it can only be used for doPost)
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
System.out.println("编码方式" + req.getCharacterEncoding());
String parameterValue = req.getParameter("userName");
System.out.println(parameterValue);
}
If the POST is still garbled after adding the first line of code, even GET is also garbled, it can be considered that the console output is garbled
Solution: [Click Edit Configuration, enter in VM Options]-Dfile.encoding=utf-8
(The solution of this method is effective for both POST and GET: the function is to solve the garbled output of the console) Reference 1 Reference 2
If after using the above two methods, the Chinese from the browser is not garbled, but the Chinese in the code is garbled again, you can consider entering [Settings - Editor - File Encdings] to set it
example
<form action="/web2/postWeb" method="GET">
请求参数:<input type="text" name="userName"/>
<br/>
<input type="submit" value="POST方式访问Servlet">
</form>
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
System.out.println("编码方式" + req.getCharacterEncoding());
String parameterValue = req.getParameter("userName");
System.out.println(parameterValue);
<!--Servlet实现类PostServlet的配置-->
<servlet>
<servlet-name>MyPostServlet</servlet-name>
<servlet-class>controller.PostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyPostServlet</servlet-name>
<url-pattern>/postWeb</url-pattern>
</servlet-mapping>