Difference between forward and redirect

Source: Internet
Author: User

Difference between forward and redirect in Servlet (08:44:55)
Tags: servlet it classification: J2SE
Forward method: request. getRequestDispatcher ("/somePage. jsp"). forwardrequest, response );
Redirect mode: response. sendRedirect ("/somePage. jsp ");
Forward is the internal redirection of the server. After the program receives the request, it is redirected to another program, and the client does not know it. redirect means that the server sends a status header to the customer after receiving the request, and the customer will send a request again, there are two more network communications. Of course, forward also has a disadvantage, that is, if the forward page path is a relative path, there will be some problems. Forward will include the request state, bean, and other information to the next jsp
The redirect request is sent to the client again, so the data is not retained.
With forward, you can use getAttribute () to obtain the bean put by the previous jsp and other information.

I saw some posts on the Internet and summarized some differences, which can be viewed from the following aspects:

1. From the address bar

Forward is a server request resource. The server directly accesses the URL of the target address, reads the response content of that URL, and then sends the content to the browser. the browser does not know where the content sent by the server comes from, so its address bar is still the original address.

Redirect is a status code sent by the server based on logic, telling the browser to request the address again. the new URL is displayed in the address bar. therefore, redirect is equivalent to sending two requests to the server and receiving two response requests.

2. Data Sharing

Forward: the forwarding page and the forwarded page can share the data in the request.
Redirect: data cannot be shared.

Redirect can not only redirect to other resources of the current application, but also to resources of other applications on the same site, or even resources of other sites using absolute URLs.

Forward: The method can only forward requests between resources in the same Web application. forward is an operation within the server.
Redirect is used by the server to notify the client to initiate a request again.

Therefore, you can say that redirect is an indirect request, but you cannot say "whether a request belongs to forward or redirect"


3. From the usage perspective

Forward: It is generally used when a user logs on to the corresponding module based on the role.

Redirect: It is generally used to return to the home page and jump to other websites when a user logs out.

4. Efficiency
Forward: High.
Redirect: low.

5. jsp syntax

<Jsp: forward page = {"relativeurl" | "<% = expression %>"}/>

Or write as follows:

<Jsp: forward page = {"relativeurl" | "<% = expression %>"}>


<Jsp: param name = "parametername" value = "{parametervalue | <% = expression % >}"/> +


</Jsp: forward>

6. Example

<Jsp: forward page = "/servlet/login. jsp"/>

<Jsp: forward page = "/servlet/login. jsp">

<Jsp: param name = "username" value = "jsmith"/>

</Jsp: forward>

Description

<Jsp: forward> the tag transfers a request object containing user requests from one jsp file to another. <jsp: forward> the code below the tag cannot be executed.


You can send parameters and values to the target file. In this example, the parameter name is username and the value is scott. If you use the <jsp: param> label, the target file must be a dynamic file that can process parameters.


If you use non-buffered output, be careful when using <jsp: forward>.
If the jsp file already has data before you use <jsp: forward>, the file execution will fail.

Attribute

Page = "{relativeurl | <% = expression %> }"
Here is an expression or a string used to indicate the file or url you want to target. this file can be jsp, program segment, or other files (such as asp, cgi, php) that can process request objects ).

<Jsp: param name = "parametername" value = "{parametervalue | <% = expression % >}"/> +
Send one or more parameters to a dynamic file. This file must be a dynamic file.

If you want to pass multiple parameters, you can use multiple <jsp: param> In a jsp file. Name specifies the parameter name and value specifies the parameter value.

 

<Jsp: forward> example

<% @ Page contentType = "text/html; charset = gb2312" %>

<Html>

<Head>

<Title> test </title>

</Head>

<Body>

<Jsp: forward page = "forwardTo. jsp">

<Jsp: param name = "userName" value = "riso"/>

</Jsp: forward>

</Body>

</Html>

ForwardTo. jsp

<% @ Page contentType = "text/html; charset = gb2312" %>

<! -- ForwardTo. jsp -->

<%

String useName = request. getParameter ("userName ");

String outStr = "Thank you! ";

OutStr + = useName;

Out. println (outStr );

%>

Redirect example:

For example, the client uses XXX \ index. jsp? Name = gauss & pwd = 123 access index. jsp, and index. <jsp: forward page = "login. jsp "/>, In the login. in jsp, you can use request. getParameter () gets the name and pwd, while <% response. sendRedirect ("login. jsp "); %> Not available.

Bytes --------------------------------------------------------------------------------------------------

In Java Web development, page Jump methods are often used. The following two methods are generally used.
Java code
HttpServletResponse response = new HttpServletResponse ();
Response. sendRedirect (location );
RequestDispatcher rd = new RequestDispatcher ();
Rd. forward (request, response );
Redirect Mode
Http: // localhost: 8080/Test application
The forward method can be used to redirect only one resource in the same Web application. The sendRedirect method allows you to redirect to any URL.
The form action = "/uu"; sendRedirect ("/uu"); indicates the root path relative to the server. For example, http: // localhost: 8080/Test application (submit to http: // localhost: 8080/uu );
"/Uu" in the Forward code indicates the path relative to the WEB application. For example, http: // localhost: 8080/Test application (submit to http: // localhost: 8080/Test/uu );
(Use the Forward method of the RequestDispatcher Interface)
Forward () cannot be redirected to a jsp file with a frame. It can be redirected to an html file with a frame,
At the same time, forward () cannot be followed by parameters, such as servlet? Name = frank. If this is not the case, you can use response. setAttribute ("name", name) in the program to upload it to the next page.
The URL in the browser address bar remains unchanged after redirection.
The forward method can be called only when the client has no output. If the buffer on the current page is not empty, you must clear the buffer before calling the forward method.
"/" Indicates the relative web Application Path
RequestDispatcher rd = request. getRequestDispatcher ("/ooo");
Rd. forward (request, response); Submit to http: // localhost: 8080/Test/ooo
RequestDispatcher rd = getServletContext (). getRequestDispatcher ("/ooo");
Rd. forward (request, response); Submit to http: // localhost: 8080/Test/ooo
RequestDispatcher rd = getServletContext (). getNamedDispatcher ("TestServlet"); (TestServlet is a <servlet-name>)
Rd. forward (request, response); Submit to the servlet named TestServlet
If there are a lot of output before <jsp: forward>, and the previous output will automatically output to the client when the buffer is full, this statement will not work, so pay special attention to this.
Note: The browser address cannot be changed. Refresh will cause repeated submission.
Forward from http: // localhost: 8080/Test/gw/page. jsp
<Jsp: forward page = "OtherPage. jsp"/> after the JSP page is parsed, it is converted to pageContext. forward ("OtherPage. jsp [...]

Bytes --------------------------------------------------------------------------------------------------
Clear the current cache:
In the previous JSP Example, The out object is used. You can use this object on the JSP webpage without having to declare it in advance. This is an implicit object provided by JSP.
(Implicit Object). After the conversion is Servlet, The out Object is converted to the Object corresponding to the javax. servlet. jsp. JspWriter type.
JspWriter directly inherits from java. io. Writer. You can use the println () and print () Methods to transmit the specified data to the client in character mode.
Line feed is performed after the data is sent, while print () is not. Note that line feed refers to setting line feed characters in the original HTML code, rather than outputting <br> labels so that the web page can
Line feed.
Out (JspWriter) has the buffer function. HTTP is used to obtain a resource and communicate with each other in a Protocol. If there are many resources (such as an HTML file ),
It also includes a lot of small images), and the capacity of each resource is actually very small, so in order to obtain the complete resources, it will spend a lot of communication on protocol exchanges, assuming that if
Out (JspWriter) does not have the buffer function. Every time out. println () is sent directly to the client, the data must be transmitted to a complete webpage.
It will consume a lot of network resources, and each JSP page will be buffered by default. You can use the autoFlush attribute of the page directive element to set whether to use the buffer function.
.
On Tomcat5, A 8192-byte buffer is pre-configured for each JSP page (you can use the buffer attribute of the page directive element from the buffer size ).
Data is not actually sent to the client before it is full. Before that, you may reset the data to be sent. If the buffer is full, the data will be cleared and sent to the customer.
End, you can use the following program to demonstrate:
Buffer. jsp
<% @ Page contentType = "text/html; charset = Big5" %>
<%
Out. println ("default buffer size:" + out. getBufferSize () + "<br> ");
Out. flush ();
// The text below will not appear on the client
Out. println ("Have you seen this text? ");
Out. clearBuffer ();
Out. println ("You can see this section! ");
%>
You can use flush () to directly clear the buffer content, while clearBuffer () will clear the buffer content, so the second paragraph of text will not appear on the client's webpage,
The final part is automatically sent to the client after the entire JSP page is executed. The execution result is as follows:
Default buffer size: 8192
You can see this section!
You can use autoFlush of the page command element to set whether the JSP page uses the automatic buffer clearing function. out (JspWriter)
The PrintWriter of HttpServletResponse establishes a relationship. The behavior relationship between the two depends on whether the buffer zone is used for automatic clearing. If the buffer zone is used for automatic clearing
The PrintWriter object is not created before the buffer is full or before the flush () is used to output the client. If the buffer is not used for automatic cleaning, the output is written
(JspWriter) the data of the object is directly written to the PrintWriter object, and then output to the client after the flush () is specified.
If you set autoFlush to false, you must explicitly use flush () to output data. Otherwise, if the buffer is full, an IOException occurs.
The buffer zone has its advantages. However, because the data is not actually sent to the client before the buffer zone is full, there will be a problem of response latency. If you want to respond to the client in real time
You can disable the buffer.
What will happen if the buffer is full after the buffer is closed in the following program:
Buffer. jsp
<% @ Page contentType = "text/html; charset = Big5" %>
<%
For (int I = 0; I <2000; I ++ ){
Out. println ("test ");
// Out. flush ();
}
%>
If the out. flush () annotation is not removed, the following error message is returned:
HTTP Status 500-
Type Exception report
Message
Description The server encountered an internal error () that prevented it from fulfilling this request.
Exception
Java. io. IOException: Error: JSP Buffer overflow
......

Author andy"
 

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.