Service redirection for Java: The difference between forwarding requests using the forward () method and redirecting using the Sendredirect () method

Source: Internet
Author: User

Forwarding requests using the forward () method of the Requestdispatche R and using HttpServletResponse's Sendredirect () method redirection can make the page go to another page, and now collect the difference between the two:

I. Requestdispatcher.forward () method
Forward is the server requests the resource, the server directly accesses the URL of the destination address, reads the response content of that URL, and then sends the content to the browser, the browser does not know where the server sends the content from, so its address bar is the original address.
A service party (such as a servlet) forwards the request to another servlet (or JSP) in the same Web application-a third party to process (the process browser-the client does not know), and let the third party directly return the results to the browser side.
The code that is typically used in the servlet is:

Request.getrequestdispatcher (the URL of the jump page). foward (Request,response);

How to get RequestDispatcher

There are three ways to get the request dispatcher object.

1.javax.servlet. The ServletRequest getrequestdispatcher (String path) method, where path can be a relative path, but cannot be more out of the current servlet context. If path begins with "/", it resolves to the root relative to the current context.

2.javax.servlet. ServletContext the Getrequestdispatcher (String path) method, where path must begin with "/" and the path is relative to the current servlet context. You can call ServletContext's GetContext (String Uripath) to get another servlet context, and you can turn to a server resource link to the external context.

3. Use Javax.servlet. ServletContext's Getnameddispatcher (String name) gets a Web resource named name, including Servlets and JSP pages. The name of this resource is specified in the Web application Deployment description file, XML.

There are subtle differences in the use of these three methods. For example, an application configuration file, Web. XML, which defines two servlets, named Firstservlet and Secondservlet, respectively, with the corresponding classes Org.javaresearch. redirecttest. Servletone and Org. Javaresearch.redirecttest.ServletTwo. can be accessed in the browser via a link similar to the following: http://localhost:8080/servlet/firstservlet/
Use the 1 method, for example, in Firstservlet to write the following code:

RequestDispatcher rd = Request.getrequestdispatcher ("Secondservlet"); Rd.forward (request, response);

At this point control is shifted to the second servlet.

Using the method in 2, you can get the RequestDispatcher code from the servlet context as follows:

RequestDispatcher rd = Getservletcontext (). Getrequestdispatcher ("/servlet/secondservlet"); Rd.forward (Request, Response);

Use the method in 3 from the web above. The XML configuration file can see two servlets defined, named Firstservlet and Secondservlet, so you can get the name dispatcher:

RequestDispatcher rd = Getservletcontext (). Getnameddispatcher ("Secondservlet"); Rd.forward (request, response);

This can also redirect to Secondservlet.

Two. Sendredirect () method
Response.sendredirect (Jump page URL)
Is the server based on logic, send a status code (location, status code 320), tell the browser to request the address again, in general, the browser will use all the parameters just requested again, so the session,request parameters can be obtained.
A service party (such as a servlet) directly sends the destination URL back to the browser, allowing the browser to automatically re-issue an HTTP request to the destination URL itself.
Redirection is viewed as a different request.


Three. How to choose
The difference between the Requestdispatcher.forward () method and the Httpservletresponse.sendredirect () method is that the former is only the steering of the control in the container, and the address in the client browser address bar does not appear The latter is a full jump, the browser will get the address of the jump, and resend the request link. This way, you can see the link address after the jump from the address bar of the browser. Therefore, the former is more efficient, when the former can satisfy the need, try to use the request Dispatcher.forward () method, and this also helps to hide the actual link. In some cases, for example, you need to jump to a resource on a different server, you must use the Httpservletresponse.sendrequest () method.

Ps:

1. Jump to the specified page with Sendredirect in the filter, which is normally displayed as shown below.

String ContextPath = Httpservletrequest.getcontextpath (); Httpservletresponse.sendredirect (ContextPath + "/ Alert.html ");

However, in the filter with forward jump to the specified page, because the specified page ContextPath and the current request ContextPath different, causing the jump to the specified page can not load the page needs other resource files, such as. css,. js,. IMG and other resources.

Request.getrequestdispatcher ("/error.jsp"). Forward (HttpServletRequest, httpservletresponse);

Forward go to the page, you need to set base, as follows:

<%@ page contenttype= "Text/html;charset=utf-8" language= "java" pageencoding= "UTF-8" iserrorpage= "true"%><%    request.setcharacterencoding ("Utf-8");    String path = Request.getcontextpath ();    String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE html>...

2.forward method of passing parameters

Request.getrequestdispatcher ("/test/forward.do?name=" +name). Forward (HttpServletRequest, httpservletresponse);
Get parameters in Forwardcontroller
@RestController @requestmapping ("Test") public class Forwardcontroller extends Abstractbasecontroller {        @ Requestmapping (value = "/forward.do", method = requestmethod.post) public    limitrspinfo alert (httpservletrequest Request, HttpServletResponse response) {        String name = Request.getparameter ("name");        ...    }}

Service redirection for Java: The difference between forwarding requests using the forward () method and redirecting using the Sendredirect () method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.