[Java Web] Forward and Redirect

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, requestand the responseobject is forwarded by the server and has not changed, so the two objects are attributealso kept intact.

Redirect

Redirection is a client-side behavior. After the user request arrives at the server, the server returns a response with the HTTPstatus code set to 302, and saves the forwarded page in the Locationattribute 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 requestand responseobjects are different before and after the redirect , and the two objects are differentattribute before and after the redirect .

Redirects can access Webresources outside the current application.

Simple illustration


Forward Forward

write picture description here

Redirect

write picture description here

Intuitively


Forward Forward

To /servletTestinitiate a request:
write picture description here
The address in the address bar has not changed.

Redirect

To /servletTestinitiate a request:
write picture description here
The address in the address bar has changed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906575&siteId=291194637