“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”
First, it
Each time a request comes into Tomcat, the Tomcat server parses the HTTP protocol information into an HttpServletRequest object and passes it to the Service method. The HttpServletRequest object is used to retrieve information from requests sent by clients
Common methods of HttpServletRequest
- GetRequestURI () to get the requested resource path
- GerRequestURL (), which gets the uniform resource locator for the request
- GetRemoteHost () to obtain the client IP address
- GetHeader () to get the request header
- GetParameter (), gets the parameters of the request
- GetParameterValues (), which gets the values of multiple parameters in the request
- GetMethod (), which gets the request method, GET or POST
- SetAttribute (key,value) : Sets domain data
- GetAttribute (key) to obtain domain data
- GetRequestDispatcher (), gets the request forward object
Add HiServlet to the Controller package
public class HiServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Obtain the requested resource path
System.out.println("Requested resource path is:" + req.getRequestURI());
// 2. Get the requested URL
System.out.println("The requested URL is:" + req.getRequestURL());
// 3. Obtain the client IP address
System.out.println("The client IP address is:" + req.getRemoteHost());
// 4. Get the request header
System.out.println("Request header:" + req.getHeader("User-Agent"));
// 5. Obtain the request mode
System.out.println("Request form:"+ req.getMethod()); }}Copy the code
Configure the access path for the Servlet in web.xml
<servlet>
<servlet-name>HiServlet</servlet-name>
<servlet-class>com.lilith.servlet.HiServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HiServlet</servlet-name>
<url-pattern>/hi</url-pattern>
</servlet-mapping>
Copy the code
Restart Tomcat and visit http://localhost:8080/hi
Add form. HTML page in web directory, add a form
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Form</title>
</head>
<body>
<form action="/param" method="get">User name:<input type="text" name="username"> <br>Password:<input type="password" name="password"> <br>Hobbies and Interests:<input type="checkbox" name="hobby" value="cpp"> C++
<input type="checkbox" name="hobby" value="java"> Java
<input type="checkbox" name="hobby" value="python"> Python <br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Copy the code
New ParamServlet class to get data from form submission
public class ParamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get the parameters in the request
String username = req.getParameter("username");
String password = req.getParameter("password");
String hobby = req.getParameter("hobby");
System.out.println("The value of username in the request is:" + username);
System.out.println(The value of the password parameter in the request is: + password);
System.out.println(The value of the hobby parameter in the request is: + hobby);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp); }}Copy the code
Add the ParamServlet access configuration to web.xml
<servlet>
<servlet-name>ParamServlet</servlet-name>
<servlet-class>com.lilith.servlet.ParamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ParamServlet</servlet-name>
<url-pattern>/param</url-pattern>
</servlet-mapping>
Copy the code
Restart the Tomcat, the browser enter http://localhost:8080/form.html, input data in the form and then click the submit
If a parameter has multiple values, you need to use getParameterValues. GetParameter can only obtain the first value of a parameter
// Get the parameters in the request (multiple values)
String[] hobbies = req.getParameterValues("hobby");
System.out.println("All values of the hobby parameter in the request:" + Arrays.asList(hobbies));
Copy the code
Chinese garbled characters
Enter Chinese in the form and click Submit
When the request mode is GET, Chinese characters can be displayed normally
Change the request mode in form.html to POST, copy the code from the goGet method to the doPost method, and submit the Chinese information in the form again
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("DoPost method called!");
// Get the parameters in the request
String username = req.getParameter("username");
String password = req.getParameter("password");
String hobby = req.getParameter("hobby");
System.out.println("The value of username in the request is:" + username);
System.out.println(The value of the password parameter in the request is: + password);
System.out.println(The value of the hobby parameter in the request is: + hobby);
// Get the parameters in the request (multiple values)
String[] hobbies = req.getParameterValues("hobby");
System.out.println("All values of the hobby parameter in the request:" + Arrays.asList(hobbies));
}
Copy the code
According to the console output, Chinese characters are garbled when the POST method is submitted.
Added encoding Settings to the doPost method
req.setCharacterEncoding("UTF-8");
Copy the code
Submit the form again
Chinese garbled characters have been solved
Servlet request forwarding
Request forwarding refers to the operation of a server to jump from one resource to another after receiving a request.
Create two new Servlet classes, AlphaServlet and BravoServlet, in the Controller package to implement request forwarding
public class AlphaServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get the request parameters
String username = req.getParameter("username");
System.out.println("The value of username in the alpha request is:" + username);
// The address to forward to BravoServlet
// The forwarding address must begin with a slash
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/bravo");
// Forward to BravoServletrequestDispatcher.forward(req,resp); }}Copy the code
public class BravoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
System.out.println("The bravo request parameter username has the value: + username);
System.out.println("BravoServlet business processing"); }}Copy the code
Configure the access paths for AlphaServlet and BravoServlet in web.xml
<servlet>
<servlet-name>AlphaServlet</servlet-name>
<servlet-class>com.lilith.servlet.AlphaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AlphaServlet</servlet-name>
<url-pattern>/alpha</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BravoServlet</servlet-name>
<servlet-class>com.lilith.servlet.BravoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BravoServlet</servlet-name>
<url-pattern>/barvo</url-pattern>
</servlet-mapping>
Copy the code
Restart Tomcat and type in your browserhttp://localhost:8080/alpha?username=peter,Click on the enter
F12 Open the browser’s check page and check the network to determine that only one request was made from the request AlphaServlet and then forward to BravoServlet. That is to say, the request AlphaServlet and the forward to BravoServlet are the same request. So the value of the username parameter is available in both servletsAnd the browser’s address bar hasn’t changed.
Request forwarding has access to files in web-INF
Create a success.html page under WEB-INF
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>SUCCESS</title>
</head>
<body>
<h1>The command is successfully forwarded to the WEB-INF directory</h1>
</body>
</html>
Copy the code
Modify the AlphaServlet to forward it to the success.html page
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/success.html");
Copy the code
Restarting the application
The browser outputs the contents of the SUCCESS page and forwards the files that can be accessed under web-INF
Characteristics of request forwarding
- The browser address bar has not changed
- It’s the same request
- Share data in the Request domain
- You can forward it to the WEB-INF directory
- Resources outside the project cannot be accessed
Relative and absolute paths on the Web
In JavaWeb, paths are divided into relative paths and absolute paths relative paths
- . : indicates the current directory
- . : indicates the upper-level directory
- Resource name: indicates the current directory or resource
An absolute path
- http://ip:port/ Project path/resource path
Different meanings of “/” on the Web
On the Web, / is an absolute path
- / If the browser parses the url, the obtained address is http://ip:port/
- / If the address is resolved by the server, the address is http://ip:port/ project path
- If the redirection address is /, the address is http://ip:port/ and the address is sent to the browser for resolution
Second, the HttpServletResponse
HttpServletResponse, like the HttpServletRequest class, Tomcat creates a Response object and passes it to the Servlet every time a request comes in. HttpServletRequest represents the information sent by the request. HttpServletResponse represents information about all responses; If a message needs to be returned to the client, it can be set up using an HttpServletResponse object
HttpServletResponse uses the output stream to send messages to the client
- Byte stream, getOutputStream(); Often used for downloading (passing binary data)
- Character stream, getWriter(); Common and postback strings (common)
Another stream can only use one at a time.
Create a SteamServlet class in the Controller package using both a character stream and a byte stream
public class StreamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter(); resp.getOutputStream(); }}Copy the code
Configure the access path for the Servlet in web.xml
<servlet>
<servlet-name>SteamServlet</servlet-name>
<servlet-class>com.lilith.servlet.StreamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SteamServlet</servlet-name>
<url-pattern>/stream</url-pattern>
</servlet-mapping>
Copy the code
Restart the Tomcat, the browser enter http://localhost:8080/stream
Page error
Modify the StreamServlet to use only character streams
public class StreamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
// resp.getOutputStream();
writer.write("Response Content"); }}Copy the code
Restart Tomcat, and enter in the browserhttp://localhost:8080/stream The browser returns a response message
Solution 1 to the Problem of Chinese garbled characters
Set the content returned in StreamServlet to Chinese format and restart Tomcat with the browser entering the same addressGarbled characters are displayed on the page
Get the character encoding in the code, restart Tomcat, and access the same address
Set the encoding format of the response in your code
public class StreamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Set the UTF-8 encoding
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
// resp.getOutputStream();
String characterEncoding = resp.getCharacterEncoding();
System.out.println("The character is encoded as:" + characterEncoding);
writer.write("Here's the response."); }}Copy the code
Restart Tomcat and access /streamStill appear garbled phenomenon
The browser character set also needs to be set through the request header
public class StreamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Set the UTF-8 encoding
resp.setCharacterEncoding("UTF-8");
// The response header sets the UTF-8 character set
resp.setHeader("Content-Type"."text/html; charset=UTF-8");
PrintWriter writer = resp.getWriter();
// resp.getOutputStream();
String characterEncoding = resp.getCharacterEncoding();
System.out.println("The character is encoded as:" + characterEncoding);
writer.write("Here's the response."); }}Copy the code
Restart Tomcat and access /streamChinese can be displayed normally
Solution 2 to the Problem of Chinese garble
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Set the UTF-8 encoding
// resp.setCharacterEncoding("UTF-8");
// The response header sets the UTF-8 character set
// resp.setHeader("Content-Type","text/html; charset=UTF-8");
// A code solution
resp.setContentType("text/html; charset=UTF-8");
PrintWriter writer = resp.getWriter();
// resp.getOutputStream();
String characterEncoding = resp.getCharacterEncoding();
System.out.println("The character is encoded as:" + characterEncoding);
writer.write("Here's the response.");
}
Copy the code
Using resp. SetContentType (” text/HTML; Charset =UTF-8″) allows both the server and client to be utF-8 encoded and the response header to be set, and this method must be called before the stream object is fetched
Restart Tomcat and access /stream again
Request redirection
Request redirection refers to that after the client sends a request to the server, the server returns a new address, and the client accesses this new address again. This is called the redirection of the request.
Create two new servlets in the Controller package to redirect the request
public class DeltaServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(this.getClass().getName());
resp.setStatus(302);
resp.setHeader("Location"."http://localhost:8080/echo"); }}Copy the code
public class EchoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(this.getClass().getName());
resp.getWriter().write(this.getClass().getName()); }}Copy the code
Configure access paths for both servlets in web.xml
<servlet>
<servlet-name>DeltaServlet</servlet-name>
<servlet-class>com.lilith.servlet.DeltaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DeltaServlet</servlet-name>
<url-pattern>/delta</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>EchoServlet</servlet-name>
<servlet-class>com.lilith.servlet.EchoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EchoServlet</servlet-name>
<url-pattern>/echo</url-pattern>
</servlet-mapping>
Copy the code
Restart Tomcat and enter it in your browserhttp://localhost:8080/delta
You can determine some of the characteristics of request redirection based on what the browser displays
- The browser address bar changes after the request is redirected
- The request redirection actually occurred twice
- Request redirection does not share data in the Request domain
Test whether the redirect can be redirected to the WEB-INF page
resp.setHeader("Location"."http://localhost:8080/WEB-INF/success.html");
Copy the code
Restarting the application
If the access fails, the redirection cannot access the resources in web-INF. However, the redirection can query the resources outside the project
Second implementation of request redirection (recommended)
resp.sendRedirect("http://localhost:8080/echo");
Copy the code
Instead of setting the response code and header
public class DeltaServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(this.getClass().getName());
// resp.setStatus(302);
// // resp.setHeader("Location","http://localhost:8080/echo");
// resp.setHeader("Location","http://localhost:8080/WEB-INF/success.html");
resp.sendRedirect("http://localhost:8080/echo"); }}Copy the code
Restarting an application still enables redirection. The second method is recommended