当前位置:网站首页>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
边栏推荐
- 【shell脚本】使用菜单命令构建在集群内创建文件夹的脚本
- Pytest parameterization some tips you don't know / pytest you don't know
- Heap (priority queue) topic
- Reids之删除策略
- CSP student queue
- [OC-Foundation框架]---【集合数组】
- Redis cluster
- [shell script] use menu commands to build scripts for creating folders in the cluster
- Persistence practice of redis (Linux version)
- Selenium+pytest automated test framework practice
猜你喜欢
Parameterization of postman
postman之参数化详解
Advanced Computer Network Review(4)——Congestion Control of MPTCP
Export IEEE document format using latex
Advanced Computer Network Review(5)——COPE
The carousel component of ant design calls prev and next methods in TS (typescript) environment
数学建模2004B题(输电问题)
如何正确截取字符串(例:应用报错信息截取入库操作)
How to intercept the string correctly (for example, intercepting the stock in operation by applying the error information)
【文本生成】论文合集推荐丨 斯坦福研究者引入时间控制方法 长文本生成更流畅
随机推荐
LeetCode:236. The nearest common ancestor of binary tree
CSP student queue
LeetCode:498. Diagonal traversal
[oc]- < getting started with UI> -- learning common controls
Leetcode: Jianzhi offer 03 Duplicate numbers in array
SimCLR:NLP中的对比学习
Export IEEE document format using latex
CSP salary calculation
AcWing 2456. 记事本
Advanced Computer Network Review(5)——COPE
如何正确截取字符串(例:应用报错信息截取入库操作)
【shell脚本】——归档文件脚本
An article takes you to understand the working principle of selenium in detail
The carousel component of ant design calls prev and next methods in TS (typescript) environment
Redis之哨兵模式
[OC foundation framework] - [set array]
Multivariate cluster analysis
BN folding and its quantification
Pytorch view tensor memory size
Mathematical modeling 2004b question (transmission problem)