Forward and redirect, forwardredirect

Source: Internet
Author: User

Forward and redirect, forwardredirect
Forward and redirect

1. Use the forward method

Request. getRequestDispatcher (path). forward (request. response );

First, let's take a look at the getRequestDispatcher method. The path must be a relative path.
GetRequestDispatcher
RequestDispatcher getRequestDispatcher(String path)
Returns RequestDispatcherObject that acts as a wrapper for the resource located at the given path. RequestDispatcherObject can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.

The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. This method returnsnullIf the servlet container cannot returnRequestDispatcher.

The difference between this method andServletContext.getRequestDispatcher(java.lang.String)Is that this method can take a relative path.

 

Parameters:
path- StringSpecifying the pathname to the resource. If it is relative, it must be relative against the current servlet.
Returns:
A RequestDispatcherObject that acts as a wrapper for the resource at the specified path, or nullIf the servlet container cannot return RequestDispatcher
See Also:
RequestDispatcher, ServletContext.getRequestDispatcher(java.lang.String)
Then the forward method, forward
void forward(ServletRequest request,             ServletResponse response)             throws ServletException,                    IOException
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. this method allows one servlet to do preliminary processing of a request and another resource to generate the response.

ForRequestDispatcherObtainedgetRequestDispatcher(),ServletRequestObject has its path elements and parameters adjusted to match the path of the target resource.

forwardShocould be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throwsIllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be subclasses ofServletRequestWrapperOrServletResponseWrapperClasses that wrap them.

 

Parameters:
request- ServletRequestObject that represents the request the client makes of the servlet
response- ServletResponseObject that represents the response the servlet returns to the client
Throws:
ServletException-If the target resource throws this exception
IOException-If the target resource throws this exception
IllegalStateException-If the response was already committed
2. The sendRedirect method uses sendRedirect in HttpServletResponse to achieve redirection and can accept relative or absolute paths. SendRedirect
public void sendRedirect(java.lang.String location)                  throws java.io.IOException
Sends a temporary redirect response to the client using the specified redirect location URL. this method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. if the location is relative without a leading '/'the iner interprets it as relative to the current request URI. if the location is relative with a leading '/'the iner interprets it as relative to the servlet container root.

If the response has already been committed, this method throws an IllegalStateException. After using this method, the response shocould be considered to be committed and shocould not be written.

 

Parameters
Positioning-The redirect location URL
Throws:
java.io.IOException-If an input or output exception occurs
java.lang.IllegalStateException-If the response was committed or if a partial URL is given and cannot be converted into a valid URL

ServletJumpRedirectAndForwardJump differences

Servlet:

Of course, in servlet, the jump usually occurs in methods such as doGet and doPost.

I. Principles

1) redirect Mode

Response. sendRedirect ("/a. jsp ");

The path of the page is relative. SendRedirect can jump the page to any page, which may not be limited to this web application, for example:

Response. sendRedirect ("http://www.ycul.com ");

The browser address bar changes after the jump.

In this way, values can only be transmitted with parameter in the url or in the session. request. setAttribute cannot be used.

This method is used for redirection on the client. This method modifies the http header to issue a redirection command to the browser, so that the browser can request the URL specified in the location to display the content of the redirected webpage. This method can accept absolute or relative URLs. If the parameter passed to this method is a relative URL, Web container converts it into an absolute URL before sending it to the client. Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{

Response. setContentType ("text/html; charset = UTF-8 ");

Response. sendRedirect ("/index. jsp ");

}

2) forward mode

RequestDispatcher dispatcher = request. getRequestDispatcher ("/a. jsp ");

Dispatcher. forward (request, response );

The path of the page is relative. The forward method can only jump to the page in this web application.

The browser address bar does not change after the jump.

In this way, you can use three methods for transferring values: url with parameter, session, request. setAttribute

This method is a redirection on the server side. The server sends data to the client in the following way: before sending data to the client, the server first outputs the data to the buffer and then sends the data in the buffer to the client. When will the data in the buffer be sent to the client? (1) When the request from the client is processed and all data is output to the buffer, (2) when the buffer is full, (3) the buffer output method out is called in the program. flush () or response. flushbuffer (), web container sends data in the buffer to the client.

This redirection method uses the server-side buffer mechanism. before sending the data in the buffer to the client, the original data is not sent, and the execution is redirected to the redirect page to send the data on the redirect page, data on the Redirect call page will be cleared. If there are a lot of output before <JSP: FORWORD>, and the previous output will automatically output to the client when the buffer is full, this redirection method will not work, so pay special attention to this.

Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{

Response. setContentType ("text/html; charset = UTF-8 ");

ServletContext SC = getServletContext ();

RequestDispatcher rd = null;

Rd = SC. getRequestDispatcher ("/index. jsp ");

Rd. forward (request, response );

}

Ii. Differences.

1. forward redirection is the redirection of the same Web application implemented in the container. Therefore, the forward method can only redirect to one resource in the same Web application. After the redirection, the URL in the browser address bar remains unchanged, the sendRedirect method can redirect to any URL, because this method is implemented by modifying the http header. There is no restriction on the URL. After the redirection, the URL in the browser's address bar changes.

2. forward redirection transmits the original HTTP request object (request) from one servlet instance to another instance, while sendRedirect is not the same application.

3. Based on the second point, the parameter transmission method is different. The form parameter of forward is passed along, so the parameters of the HTTP request can be obtained in the second instance. SendRedirect can only pass parameters through links, response. sendRedirect ("login. jsp? Param1 = ").

4. sendRedirect can process relative URLs and automatically convert them into absolute URLs. if the address is relative, there is no '/', the Web iner considers it relative to the current request URI. For example, if it is response. sendRedirect ("login. jsp "), login will be searched from the URL path of the current servlet. jsp: http: // 10.1.18.8: 8081/dms/servlet/Servlet redirect URL: http: // 10.1.18.8: 8081/dms/servlet/login. jsp. If it is response. sendRedirect ("/login. jsp "), the url: http: // 10.1.18.8: 8081/login will be searched from the current application path. jsp. Forward cannot process relative paths in this way.

Java

Their differences are:

Response. sendRedirect is to send the page redirection command to the client browser. After receiving the request, the browser resends the page request to the web server. Therefore, after the browser is executed, the url displays the page after the jump. A jump page can be any url (either the current server or other servers ).

RequestDispatcher. forward is directly processed on the server, and the processed information is sent to the browser for display. Therefore, after the processing, the page displayed in the url is the page before the jump. Send the request and response messages sent on the previous page to the next page at the same time (while response. sendRedirect cannot send the request and response information on the previous page to the next page ). Because forward is processed directly on the server, the forward page can only be on the server.

JSP:

1) response. sendRedirect ();

It is the same as servlet's response. sendRedirect () method.

Out. flush () is not allowed before this statement. If yes, an exception occurs:

Java. lang. IllegalStateException: Can't sendRedirect () after data has committed to the client.

At com. caucho. server. connection. AbstractHttpResponse. sendRedirect (AbstractHttpResponse. java: 558)

...

Browser address bar changes after jump

If you want to jump to different hosts, after the jump, the statement after this statement will continue to be executed, as if a new thread, but the response operation has no significance;

If you want to jump to the same host, the statement after this statement is executed will not jump;

2) response. setHeader ("Location ","");

No out. flush () is allowed before this statement. If yes, the page will not jump.

Browser address bar changes after jump

Only after the statement is executed

3) <jsp: forward page = ""/>

Out. flush () is not allowed before this statement. If yes, an exception occurs:

Java. lang. IllegalStateException: forward () not allowed after buffer has committed.

At com. caucho. server. webapp. RequestDispatcherImpl. forward (RequestDispatcherImpl. java: 134)

At com. caucho. server. webapp. RequestDispatcherImpl. forward (RequestDispatcherImpl. java: 101)

At com. caucho. jsp. PageContextImpl. forward (PageContextImpl. java: 836)

...

The browser address bar remains unchanged after the jump, but the address bar can only jump to the current host

Only after the statement is executed

From: http://wenku.baidu.com/link? Url = Z8dLJDFT1MX6-yDqajj71B3rc32Zx79iybgSkMoqg922FApVCTviGuYhflaWUiaMYhcAc-It1pKKq2Y127JCYp41U_y4sNsVpQ8AJ_vaEvS

Related Article

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.