当前位置:网站首页>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
边栏推荐
- Ijcai2022 collection of papers (continuously updated)
- 数学建模2004B题(输电问题)
- 如何正确截取字符串(例:应用报错信息截取入库操作)
- LeetCode:387. The first unique character in the string
- Implement window blocking on QWidget
- Intel distiller Toolkit - Quantitative implementation 3
- LeetCode:236. The nearest common ancestor of binary tree
- Once you change the test steps, write all the code. Why not try yaml to realize data-driven?
- LeetCode:39. Combined sum
- Kratos战神微服务框架(二)
猜你喜欢

LeetCode:498. Diagonal traversal

Problems encountered in connecting the database of the project and their solutions

Redis geospatial

Redis之发布订阅

What is MySQL? What is the learning path of MySQL

BN folding and its quantification

MySQL uninstallation and installation methods
![[OC-Foundation框架]--<Copy对象复制>](/img/62/c04eb2736c2184d8826271781ac7e3.png)
[OC-Foundation框架]--<Copy对象复制>

Persistence practice of redis (Linux version)

Compétences en mémoire des graphiques UML
随机推荐
After reading the programmer's story, I can't help covering my chest...
Selenium+pytest automated test framework practice
Selenium+Pytest自动化测试框架实战
Le modèle sentinelle de redis
SimCLR:NLP中的对比学习
Intel Distiller工具包-量化实现3
LeetCode41——First Missing Positive——hashing in place & swap
[OC]-<UI入门>--常用控件-UIButton
SAP ui5 date type sap ui. model. type. Analysis of the parsing format of date
CSP student queue
Once you change the test steps, write all the code. Why not try yaml to realize data-driven?
Advanced Computer Network Review(3)——BBR
Blue Bridge Cup_ Single chip microcomputer_ Measure the frequency of 555
Redis之性能指标、监控方式
[Hacker News Weekly] data visualization artifact; Top 10 Web hacker technologies; Postman supports grpc
Advanced Computer Network Review(4)——Congestion Control of MPTCP
Ijcai2022 collection of papers (continuously updated)
Show slave status \ read in G_ Master_ Log_ POS and relay_ Log_ The (size) relationship of POS
【shell脚本】——归档文件脚本
Redis之核心配置