transfer
Forward
<!-- 使用 Java 语句 -->
request.getRequestDispatcher("test.jsp").forward(request, response);
<!-- jsp 页面还可以使用标签 -->
<jsp:forward page="test.jsp" />
Redirect
<!-- 使用 Java 语句 -->
response.sendRedirect("test.jsp");
principle
Forward Forward
Forwarding is a server behavior. After a user request reaches the server, the request processing and forwarding operations are completed within the server, and then the corresponding resources are returned to the client.
In the whole process, the client only sends a request once, request
and the response
object is forwarded by the server and has not changed, so the two objects are attribute
also kept intact.
Redirect
Redirection is a client-side behavior. After the user request arrives at the server, the server returns a response with the HTTP
status code set to 302
, and saves the forwarded page in the Location
attribute in the response header, telling the client that a request should be made to this address, and then the client Make the request again.
During the whole process, the client sends at least two requests, because the requests are different, so the request
and response
objects are different before and after the redirect , and the two objects are differentattribute
before and after the redirect .
Redirects can access Web
resources outside the current application.
Simple illustration
Forward Forward
Redirect
Intuitively
Forward Forward
To /servletTest
initiate a request:
The address in the address bar has not changed.
Redirect
To /servletTest
initiate a request:
The address in the address bar has changed.