What is it
The HttpServletRequest object represents the client’s request. When the client accesses the server through HTTP, all the information in the HTTP request header is encapsulated in this object. The developer can obtain the client’s information through the method of this object.
Simply put, to get browser information, look for an HttpServletRequest object
HttpServletRequest common methods
Get client [browser] information
- The getRequestURL method returns the full URL at the time the client made the request.
- The getRequestURI method returns the resource name portion of the request line.
- The getQueryString method returns the parameter portion of the request line.
- The getPathInfo method returns additional path information in the request URL. The extra path information is what is in the request URL after the Servlet’s path and before the query parameters, starting with a “/”.
- The getRemoteAddr method returns the IP address of the client that made the request
- The getRemoteHost method returns the full hostname of the requesting client
- The getRemotePort method returns the network port number used by the client
- The getLocalAddr method returns the WEB server IP address.
- The getLocalName method returns the host name of the WEB server
Get the client request header
- GetHeader method
- GetHeaders method
- GetHeaderNames method
Get client request parameters (data submitted by the client)
- The getParameter
- GetParameterValues (String name) Method
- Method getParameterNames
- GetParameterMap method
It application
Preventing hotlinking
What is anti-theft chain? For example: I now have the latest resources of One Piece, those who want to see one Piece should see it on my website. Now people from other sites see that I have one Piece resources and want to paste my resources on his own site. So I lose my exclusive resources to a CTRL+C and CTRL+V? And anti-theft is not CRTL+C and CRTL+V by them
- So let me do a simulation. Now I have a hyperlink on my home page, pointing to the latest resources of One Piece
- When I click on it, I can see one Piece’s latest resources
- Others can copy and paste my address and put it on their web pages
-
Then I won’t be able to [have you seen my advertisement yet! . Want to see my resources, you must go through my home page to see.
-
To do this, I need to retrieve the Referer header and determine if the Referer came from my home page. If it’s not from my home page, jump back to my home page.
// Where does the page come from
String referer = request.getHeader("Referer");
// If not from my home page or directly from the address bar,
if ( referer == null| |! referer.contains("localhost:8080/zhongfucheng/index.jsp")) {// Return to the home page
response.sendRedirect("/zhongfucheng/index.jsp");
return;
}
// Execute the following statement, indicating that it is from my home page, that is no problem, as usual display
response.setContentType("text/html; charset=UTF-8");
response.getWriter().write("Luffy made XXXXxxxxxxxxxxxxxxxx");
Copy the code
- First, as expected, people click on my resources from the home page to access my latest resources
- The resource is successfully accessed
- If I type the address directly into the browser (Referer is null at this point), let’s see
- Jump back to home page, cannot access to one Piece resources
- Try again, if someone pastes my resource URL and puts a url on its web page.
- When you click on someone else’s web page
- It’s back to my home page.
Form submit data [Submit data via POST]
<form action="/zhongfucheng/Servlet111" method="post">
<table>
<tr>
<td>The user name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>gender</td>
<td>
<input type="radio" name="gender" value="Male">male<input type="radio" name="gender" value="Female">female</td>
</tr>
<tr>
<td>hobby</td>
<td>
<input type="checkbox" name="hobbies" value="Swimming">swimming<input type="checkbox" name="hobbies" value="Running">running<input type="checkbox" name="hobbies" value="Fly">fly</td>
</tr>
<input type="hidden" name="aaa" value="my name is zhongfucheng">
<tr>
<td>Where do you come from</td>
<td>
<select name="address">
<option value="Guangzhou">Guangzhou</option>
<option value="Shenzhen">shenzhen</option>
<option value="Beijing">Beijing</option>
</select>
</td>
</tr>
<tr>
<td>Details:</td>
<td>
<textarea cols="30" rows="2" name="textarea"></textarea>
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
Copy the code
- The submitted data is retrieved from Servlet111 with the following code
// Format the request character encoding
request.setCharacterEncoding("UTF-8");
// Get the value from the HTML name attribute
String username = request.getParameter("username");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
// Check box and drop box have multiple values, get multiple values
String[] hobbies = request.getParameterValues("hobbies");
String[] address = request.getParameterValues("address");
// Get the value of the text field
String description = request.getParameter("textarea");
// Get the value of the hidden field
String hiddenValue = request.getParameter("aaa"); . Various System. Out.println ()...Copy the code
- Enter data into the form
- Servlet111 gets the data from the form, and the last data from the hidden field.
Submit data in hyperlink mode
Common get methods for submitting data are: using hyperlinks, sendRedirect()
The format is as follows:
sendRedirect("The address of the servlet? Parameter name ="+ Parameter value &"Parameter name ="+ parameter value);Copy the code
- Let’s use it to bring data to the browser via hyperlinks
<a href="/zhongfucheng/Servlet111? </a> </a>Copy the code
- Receive data at Servlet111
// Receive the value as username
String username = request.getParameter("username");
System.out.println(username);
Copy the code
- Look at the bottom left corner of your browser
- The server successfully receives the data from the browser
- Also, the transfer data appears in the browser’s address bar in plain text
- SendRedirect () is similar to hyperlinks and won’t be covered here
Solve the problem of Chinese garble
Careful friends will find that when I was in for form data, have the code request. SetCharacterEncoding (” utf-8 “); What would have happened without this code? Let’s see.
- Fill in the data again
- Check the submitted data in the server, all the Chinese data are garbled
-
As I explained in a previous blog post, the Tomcat server defaults to ISO 8859-1 and the browser uses UTF-8. The Chinese data of the browser is submitted to the server, **Tomcat uses ISO 8859-1 to encode The Chinese data. When I read the data in the Servlet, I got garbled characters of course. ** While I set the request encoding to UTF-8, the garbled code is resolved.
-
Next, use get mode to transfer Chinese data, and change the form mode to GET
-
When we visited, it was garbled again!
- So I did what I did above and set the request object to UTF-8
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
Copy the code
-
It’s still garbled. Why is that? I have already set the encoding to UTF-8, according to the post mode, the garble problem has been solved! . So what’s the difference between get and POST? Why can request encoding be set in POST mode to solve the garbled problem, but not in GET mode?
-
First let’s look at how the POST method passes parameters. When we click the submit button, the Data is encapsulated in the Form Data. The HTTP request takes the entity body with it. Since the Request object encapsulates the HTTP request, the request object can be parsed into the sent Data. So just set the encoding to UTF-8 to solve the garble problem.
- In get, the data is carried from the message line and not encapsulated in the Request object, so using the Request encoding is invalid.
- It is not difficult to solve the problem of garbled get mode. Since we know that the default encoding of Tomcat is ISO 8859-1, we must use ISO 8859-1 encoding when the message body is carried to the browser.
ISO 8859-1 is used to encode the string
String name = request.getParameter("username");
// Use ISO 8859-1 to retrieve the original data
byte[] bytes = name.getBytes("ISO8859-1");
// Build the string from the raw data by setting the correct code table
String value = new String(bytes, "UTF-8");
Copy the code
The above code is a little hard to understand, so let me draw a picture to illustrate:
- After our manual conversion, let’s visit again
-
Okay, we’ve solved the garble problem.
-
In addition to manual conversion, the GET mode can also change the Configuration of the Tomcat server to resolve garbled characters. However, this mode is not recommended because it is not flexible. “
-
As we all know, the default encoding of Tomcat is ISO 8859-1. If Tomcat server is configured with UTF-8 encoding, the problem of garbled characters caused by server parsing will be solved
-
Add URIEncoding=” UTF-8 “to the Connector for port 8080 to set the Tomcat access code to UTF-8 to avoid garble
<Connector port="8080" protocol="HTTP / 1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
Copy the code
- After setting the code, we did not do any manual conversion and successfully got the data
- Of course, there is another way to change the server encoding. Set the code used by Tomcat to access this port to the page code. This change varies with the page code
<Connector port="8080" protocol="HTTP / 1.1"
connectionTimeout="20000"
redirectPort="8443" useBodyEncodingForURI="true" />
Copy the code
- Set the encoding to UTF-8
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
Copy the code
- To visit again
-
Handwritten hyperlinks with Chinese parameter problems, to URL rewrite, in JSP blog will talk about
-
Conclusion:
-
Post directly changes the encoding of the Request object
-
The GET mode requires a manual encoding conversion
-
Get can also change the encoding of the Tomcat server. It is not recommended because it will depend too much on the server.
-
Post if you can post data
Implement forward
Before about the use of the response sendRedirect () can realize the redirection, do jump is the function of page, use the request getRequestDispatcher. Forward (request, response) to realize the forward, Do the function is also page jump, what is the difference between them? Now LET me talk about forwarding
- The code is shown below
// Get the requestDispatcher object and jump to index.jsp
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.jsp");
// Call the Forward () of the requestDispatcher object for forwarding, passing in the Request and response methods
requestDispatcher.forward(request, response);
Copy the code
- Visit Servlet111
-
As mentioned above, you can submit data to the server by adding parameters to the end of the resource via sendRedirect() redirection. Can a forward submit data to the server?
-
The answer is clearly yes, and it’s used very often
-
When I talked about ServletContext, I mentioned that ServletContext can communicate with servlets. ServletContext can also be called a domain object. Request can also be called a domain object, except that the domain of the ServletContext is the entire Web application, whereas the domain of the Request represents only one HTTP request
-
Let’s use request to achieve communication between servlets, Servlet111 code
// Save zhongfucheng value with username as keyword
request.setAttribute("username"."zhongfucheng");
// Get the requestDispatcher object
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Servlet222");
// Call the Forward () of the requestDispatcher object for forwarding, passing in the Request and response methods
requestDispatcher.forward(request, response);
Copy the code
- Servlet222 code
// Get the value stored in the Request object
String userName = (String) request.getAttribute("username");
// Print the value in the browser
response.getWriter().write("i am :"+userName);
Copy the code
- Visit Servlet111 to see the effect
-
As shown in the figure above, Servlet222 succeeds in retrieving the data stored by the Request object in Servlet111.
-
Now, we can use ServletContext and Request to communicate between servlets. Which one do we use? As a general rule: Use Request when you can. Because the ServletContext represents the entire Web application, using the ServletContext consumes a lot of resources, while the Request object ends with the request and the resources are recycled. Communication between servlets using the Request domain is very common in development.
Sequence diagram of forwarding
Request forwarding details
-
The Forward method throws an IllegalStateException if part of what was written in the Servlet program has actually been sent to the client before the forward method is called. Translation: Don’t write to the browser before forwarding it
-
Let’s see if there really is an anomaly.
OutputStream outputStream = response.getOutputStream();
outputStream.write("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -".getBytes());
// Close the stream to make sure the data gets to the browser
outputStream.close();
/ / jump
request.getRequestDispatcher("/Foot").forward(request, response);
Copy the code
- The Tomcat background throws an exception when the browser can output data
- If something is written to the buffer of the Servlet engine before calling the forward method, the forward method can be executed as long as the buffer is not actually printed out to the client, and the output buffer is emptied. However, The response header field information written to the HttpServletResponse object remains valid.
The difference between forwarding and redirecting
The actual location varies with the address bar
- Forwarding takes place on the server
- Forwarding is by the server to jump, careful friends will find that when forwarding, the browser address bar is not changed, when I visit Servlet111, even if the jump to the page of Servlet222, the browser address is still Servlet111. In other words, the browser does not know the action of the forward, and the forward is transparent to the browser. Through the forwarding sequence diagram above, we can also find that forwarding is only an HTTP request, and the request and response objects in a forwarding are the same. This also explains why you can use Request as a domain object for communication between servlets.
- The redirection happens in the browser
- Redirection is redirected by the browser. During redirection, the browser address will change. As mentioned before, the principle of redirection is realized by combining the status code of Response with the Location header. This is a page jump by the browser and the implementation redirects two HTTP requests, and the Request domain object is invalid because it’s not the same request object
Use different
Many people are confused about how to write resource addresses when forwarding and redirecting. Sometimes you write the name of your app, sometimes you don’t. It’s easy to confuse people. As a rule of thumb, you should start with the resource name for servers and the application name for browsers
- Request. GetRequestDispatcher (“/resource name URI “). The forward (request, response)
- “/” represents the root directory of the application.
- Response.send (“/ Web application/resource name URI”);
- When redirected, the “/” represents the Webapps directory
The range of urls you can go to is different
- A forward is a resource that the server redirects only to the current Web application
- A redirect is a server redirect that can go to any resource
Different types of data are passed
- A forwarded Request object can pass various types of data, including objects
- Redirection can only pass strings
The jump time is different
- Forward: Jumps immediately when a jump statement is executed
- Redirection: A jump is not performed until the entire page has been executed
Which is used for forwarding or redirecting?
The difference between forwarding and redirection can also be easily summarized based on the above description **. Forwarding takes the parameters of the request before forwarding. The redirect is the new request **.
Typical application scenarios:
- Forward: Access the Servlet to process the business logic, and then forward to the JSP to display the result, unchanged URL in the browser
- Redirect: Submit the form and redirect it to another JSP to prevent the form from being resubmitted and the browser URL being changed
RequestDispatcher again that
The RequestDispatcher object calls forward() to implement forwarding as described above. RequestDispatcher also has another method, include(), which implements include.
When we write a web page, the head and tail of the web page do not need to be changed. If we use servlets to output headers and tails in multiple places, we’ll need to rewrite the code. Use the RequestDispatcher include() method to include headers and tails.
- Let’s do it! I now have servlets at the head and tail of the net
- Use Servlet111 to include the header and tail
request.getRequestDispatcher("/Head").include(request, response);
response.getWriter().write("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
request.getRequestDispatcher("/Foot").include(request, response);
Copy the code
- Go to Servlet111 and successfully include the header and tail
Open source project (5.8K STAR) :Github.com/ZhongFuChen…
If you want to follow my updated articles and shared dry goods in real time, you can search Java3y on wechat.
The content of the PDF document is typed by hand. If you don’t understand anything, you can ask me directly (the official account has my contact information).