当前位置:网站首页>Servlet learning diary 7 -- servlet forwarding and redirection
Servlet learning diary 7 -- servlet forwarding and redirection
2022-07-06 09:15:00 【herb. dr】
Catalog
One 、 Supplement to the previous content
Two 、 The present servlet There are several problems
3、 ... and 、 Separate two Servlet Problems after
5.7 forward 、 Redirect summary
One 、 Supplement to the previous content
To write Java The code is as follows , And use get Request to see the effect of the display
package com.ha.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. Get the data requested by the user
String username = req.getParameter("username");
String password = req.getParameter("password");
// 【 Set the response header 】
// setStatus: Set the status code in the status line
// resp.setStatus(200);
// setContentType: Set... In the response header Content-Type, Set the data format of the response client
resp.setContentType("text/html"); // Equivalent to :resp.setHeader("Content-Type", "text/html");
// setContentLength: Set the data length of the response client , You don't usually need to set it , The client will read the data ( This is generally used for verification )
// resp.setContentLength(1024); // Equivalent to :resp.setHeader("Content-Length", "1024");
// setHeader: Set some other information
resp.setHeader("Connection", "keep-alive");
// 【 Set response body 】
// setCharacterEncoding: Set the data encoding format of the response client
resp.setCharacterEncoding("utf-8");
// adopt resp Object to get the output stream
// Byte stream ( If you want to respond to the file data to the client , You need to use byte stream )
// ServletOutputStream outputStream = resp.getOutputStream();
// Character stream ( If you want to respond to file data -HTML file , Character stream is used )
PrintWriter printWriter = resp.getWriter();
// Data written through the stream , It will be transmitted to the client browser in the form of response text , If the browser can recognize the data , It will directly show
printWriter.println("<!DOCTYPE html>");
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta chaeset='utf-8'>");
printWriter.println("<title> Login user name and password </title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<label> user name :" + username + "<label>");
printWriter.println("<label> password :" + password + "<label>");
printWriter.println("</body>");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
This is the response header :
Two 、 The present servlet There are several problems
1、 In the above Java Business logic work such as judgment may be done in the program , It is also used to print the display effect .
2、 When there is a better page to display at the back , Will revise this Java Code .
This is to call the business logic and display the result page in the same Servlet in , There will be design problems :(1) Not in line with the principle of single function 、 The idea of performing their respective duties ;(2) It is not conducive to subsequent maintenance
Business logic should be separated from displaying results
3、 ... and 、 Separate two Servlet Problems after
problem : After the business logic and display results are separated , How to jump to the Servlet?
How the data results obtained by the business logic are transferred to the display of the results Servlet?
Four 、 forward
4.1 effect
The role of forwarding is on the server side , Send the request to other resources on the server , To jointly complete the processing of a request .
4.2 Page Jump
When invoking business logic Servlet in , Write the following code :
request.getRequestDispatcher("/ The goal is URL-pattern").forward(request, response);
4.3 Operation and code
Create a new one Java file
package com.ha.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/rs").forward(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Add the content of the configuration file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<servlet>
<servlet-name>rs</servlet-name>
<servlet-class>com.ha.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rs</servlet-name>
<url-pattern>/rs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>com.ha.servlet.AServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping>
</web-app>
visit /a
Completed the page from AServlet.java Jump to RegisterServlet.java
In the eyes of the client, always access a. Use forward When jumping , Is to jump inside the server , Address bar does not change , Belong to the same request .
4.4 Data transfer
1、forward To express a request , Is to jump inside the server , Can share the same - Time request Data in scope
(1)request Scope : Have space to store data , The scope of action is one Valid requests ( One This request can be forwarded many times )
Data can be stored in request after , Get anywhere in a request
Can transfer any data ( Basic data type 、 object 、 Array 、 Collection etc. )
(2) Save the data :request.setAttribute(key, value);
Stored in... As key value pairs request Scope .key by String type , value by 0bject type
(3) Take the data :request.gettribute(key);
adopt String Type of key visit 0bject Type of value
2、 Complete process
package com.ha.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("username", " Juan ");
req.setAttribute("password", "123456");
req.getRequestDispatcher("/rs").forward(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.ha.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = (String)req.getAttribute("username");
String password = (String)req.getAttribute("password");
resp.setContentType("text/html");
resp.setHeader("Connection", "keep-alive");
resp.setCharacterEncoding("utf-8");
PrintWriter printWriter = resp.getWriter();
printWriter.println("<!DOCTYPE html>");
printWriter.println("<html>");
printWriter.println("<head>");
printWriter.println("<meta chaeset='utf-8'>");
printWriter.println("<title> Login user name and password </title>");
printWriter.println("</head>");
printWriter.println("<body>");
printWriter.println("<label> user name :" + username + "<label>");
printWriter.println("<label> password :" + password + "<label>");
printWriter.println("</body>");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<servlet>
<servlet-name>rs</servlet-name>
<servlet-class>com.ha.servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rs</servlet-name>
<url-pattern>/rs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>com.ha.servlet.AServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping>
</web-app>
Running results :
4.5 Forwarding features
Forwarding is server behavior
Forwarding is that the browser only makes one access request
Forwarding browser address unchanged
The information transmitted between two hops is not lost , So you can go through request Transfer data 、
Forwarding can only forward requests to the same Web Components in the application
5、 ... and 、 Redirect
5.1 effect
Redirection works on the client , After the client sends the request to the server , The server responds to the client with a New request address , The client resends a new request .
5.2 Page Jump
When invoking business logic Servlet in , Write the following code
response.sendRedirect(" The goal is URL");
URL: Uniform resource identifiers (Uniform Resource Identifier), It is used to indicate a location in the server A resource , Resources in web The path in the project (/project/source)
5.3 Code implementation
visit /a Swap to /rs
5.4 Data transfer
sendRedirect When jumping , Address bar changes , Resend request on behalf of client . It belongs to two requests
response No scope , two request The data in the request cannot be shared
To transfer data : adopt UR For data transmission ("/WebProject/b?usemame=tom");
get data :request.getParameter("usemame");
5.5 Code
5.6 Redirection features
Redirection is client behavior .
Redirection is that the browser has made at least two access requests .
Redirect browser address change .
The information transmitted between redirections will be lost (request Range ).
Redirection can point to any resource , Include other resources in the current application 、 Resources in other applications on the same site 、 Resources from other sites .
5.7 forward 、 Redirect summary
When two Servlet When data needs to be transferred , choice forward forward . Not recommended sendRedirect To pass
边栏推荐
猜你喜欢
随机推荐
LeetCode:394. String decoding
An article takes you to understand the working principle of selenium in detail
使用标签模板解决用户恶意输入的问题
五层网络体系结构
IJCAI2022论文合集(持续更新中)
自定义卷积注意力算子的CUDA实现
Export IEEE document format using latex
【每日一题】搬运工 (DFS / DP)
ant-design的走马灯(Carousel)组件在TS(typescript)环境中调用prev以及next方法
requests的深入刨析及封装调用
数学建模2004B题(输电问题)
Heap (priority queue) topic
LeetCode:387. The first unique character in the string
After reading the programmer's story, I can't help covering my chest...
Pytorch view tensor memory size
[shell script] use menu commands to build scripts for creating folders in the cluster
KDD 2022论文合集(持续更新中)
Basic usage of xargs command
Redis cluster
Persistence practice of redis (Linux version)