Detailed explanation of five redirect methods for jsp pages

Source: Internet
Author: User

1. RequestDispatcher. forward ()

Is used on the server. When forward () is used, the Servlet engine transmits the HTTP request from the current Servlet or JSP to another Servlet, JSP or common HTML file, that is, your form is submitted to. jsp, in. jsp uses forward () to redirect to B. jsp. At this time, all information submitted by form is in B. jsp can be obtained, and parameters are automatically transmitted. however, 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 passed with parameters after it, 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.

For example, redirection in servlet

Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException
{
Response. setContentType (text/html; charset = gb2312 );
ServletContext SC = getServletContext ();
RequestDispatcher rd = null;
Rd = SC. getRequestDispatcher (/index. jsp); // targeted page
Rd. forward (request, response );
}

Usually used in servlet, not in jsp.

2. response. sendRedirect ()

It works on the user's browser. sendRedirect () can be passed with parameters, such as servlet? Name = frank is uploaded to the next page, and can be redirected to different hosts. sendRedirect () can be used to redirect jsp files with frame.

After redirection, the URL of the redirection page will appear in the address bar of the browser.

For example, redirection in servlet

Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException
{
Response. setContentType (text/html; charset = gb2312 );
Response. sendRedirect (/index. jsp );
}

Because response is an implicit object in the jsp page, you can use response. sendRedirect () in the jsp page to directly implement relocation.

Note:

(1) When response. sendRedirect is used, there cannot be HTML output;

This is not absolute. The absence of HTML output means that HTML cannot be sent to a browser. In fact, the current server has a cache mechanism, generally at 8 K (I mean JSP SERVER), which means that unless you disable the cache or you use out. flush () force refresh. A small amount of HTML output is allowed before sendRedirect is used.

(2) After response. sendRedirect, follow the return statement.

We already know that response. sendRedirect is switched through a browser, so there will be actual actions only after page processing is complete. Now that you have to turn, what is the significance of the subsequent output? In addition, the redirection may fail due to the subsequent output.

Comparison:

(1) Dispatcher. forward () is the redirection of control in the container. The address bar of the browser on the client does not display the redirection address;

(2) response. sendRedirect () is a complete jump. the browser will get the jump address and resend the request link. In this way, the link address after the jump is displayed in the address bar of the browser.

The former is more efficient. When the former can meet the needs, try to use the RequestDispatcher. forward () method.

Note: in some cases, to jump to a resource on another server, you must use the HttpServletResponse. sendRequest () method.

3. <jsp: forward page =/>

The underlying part is implemented by RequestDispatcher, so it carries the marks of the RequestDispatcher. forward () method.

If there are a lot of outputs before, and the previous output has filled the buffer and will be automatically output to the client, then this statement will not work. Pay special attention to this.

Note: The browser address cannot be changed. Refresh will cause repeated submission.

4. Modify the Location attribute of the HTTP header to redirect

You can directly modify the address bar to redirect the page.

The jsp file code is as follows:

<%
Response. setStatus (HttpServletResponse. SC _MOVED_PERMANENTLY );
String newLocn =/newpath/jsa. jsp;
Response. setHeader (Location, newLocn );
%>


5. When a page is displayed in JSP for several seconds, it is automatically redirected to another page.

In the html file, the following code:

<Meta http-equiv = refresh content = 300; url = target. jsp>

Its meaning: after five minutes, the page automatically becomes target.html. In the code, 300 is the refresh delay time, in seconds. Targer.html: The target page you want to switch to. If this page is set, the page is automatically refreshed.

As shown in the preceding figure, you can use setHeader to automatically redirect a page to another page after several seconds.

Key code:

String content = stayTime +; URL = + URL;
Response. setHeader (REFRESH, content );

A. encode and convert Parameters

String str = new String (request. getParameter (something). getBytes (ISO-8859-1), UTF-8 );

In this case, each parameter must be transcoded in this way. Very troublesome. However, Chinese characters can be obtained.

B. Execute the Request Encoding code at the beginning of the Request page.

Request. setCharacterEncoding (UTF-8)

Set the character set of the submitted content to the UTF-8. In this way, the page that accepts this parameter does not have to be transcoded. Direct use

String str = request. getParameter (something );

You can obtain the Chinese character parameters. However, this statement must be executed on each page. This method also has an effect on post submission. The enctype = multipart/form-data for get submission and file upload is invalid. Later, we will explain the garbled characters of the two.

C. To avoid writing request. setCharacterEncoding (UTF-8) to each page, we recommend that you use a filter to encode all JSPs. There are many examples on the Internet. You can check it for yourself.

Garbled processing for form get submission

If you use the get method to submit Chinese, the page that receives the parameter will also be garbled, this garbled cause is also caused by tomcat's internal encoding format iso8859-1. Tomcat will get the default encoding method of iso8859-1 to encode Chinese characters, encoding appended to the url, resulting in the acceptance of the page parameters are garbled /,.

Solution:

A. Use the first method in the preceding example to decode the received character and then transcode it.

B. Get goes through url submission, and the iso8859-1 encoding has been performed before entering the url. To affect this encoding, you must go to the server. useBodyEncodingForURI = true attribute is added to the Connector node of xml to control tomcat's Chinese character encoding method for get. The above attribute Controls get submission and also uses request. encode the encoding format set by setCharacterEncoding (UTF-8. So the automatic encoding is UTF-8, and the page can be accepted normally. But I think the real encoding process is that tomcat needs

<Connector port = 8080
MaxThreads = 150 minSpareThreads = 25 maxSpareThreads = 75
EnableLookups = false redirectPort = 8443 acceptCount = 100
Debug = 0 connectionTimeout = 20000 useBodyEncodingForURI = true
DisableUploadTimeout = true URIEncoding = UTF-8/>

Inside the set URIEncoding = UTF-8 again encoding, but because it has been encoded as UTF-8, encoding will not change. If the encoding is obtained from the url, the accept page is decoded Based on URIEncoding = UTF-8.

Garbled during File Upload

When uploading files, the form is set to enctype = multipart/form-data. This method submits files in streaming mode. If you use the apach Upload Component, you will find many garbled characters. This is because of a bug in the early commons-fileupload.jar of apach, Which is decoded after the Chinese characters are taken out, because this method is submitted, the encoding is automatically used by the tomcat default encoding format iso-8859-1. But the garbled problem is: periods, commas, and other special characters become garbled. If the number of Chinese characters is odd, garbled characters will occur, and even numbers will be parsed normally.

Solution:

Downloading the jar version of The commons-fileupload-1.1.1.jar has fixed these bugs.

But the extracted characters still need to be transcoded from the iso8859-1 to UTF-8. All Chinese characters and characters can be obtained normally.

Java code. For url requests, garbled parameters are accepted.

The url encoding format depends on the URIEncoding = UTF-8 mentioned above. If this encoding format is set, it means that all the Chinese character parameters to the url must be encoded. Otherwise, the obtained Chinese character parameter values are garbled, such as a link:

Response. sendDerect (/a. jsp? Name = Zhang Dawei );

And directly used in a. jsp

String name = request. getParameter (name );

Garbled characters are obtained. Because UTF-8 is required, the conversion should be written as follows:

Response. sendDerect (/a. jsp? Name = URLEncode. encode (Zhang Dawei, UTF-8 );

.

What if URIEncoding = UTF-8 is not set? If not set, the default encoding format iso8859-1 is used. The problem arises again. The first is that if the number of parameter values is an odd number, it can be parsed normally. If the number is an even number, the final character is garbled. In addition, if the last character is in English, it can be parsed normally, but the Chinese Punctuation Marks are still garbled. If your parameter does not contain Chinese Punctuation Marks, you can add an English symbol at the end of the parameter value to solve the garbled problem. After obtaining the parameter, remove the last symbol. It can also be used together.

The script code contains garbled parameters for url requests.

The script also controls page redirection, also involves parameters, and accepts the page parsing parameter. If the Chinese character parameter is not subject to the encoding specified by URIEncoding = UTF-8, the Chinese characters accepted by the page are garbled. It is troublesome for the script to process the encoding. You must have the corresponding encoding script file, and then call the method in the script to encode the Chinese characters.

About the garbled characters opened by jsp in MyEclipse

For an existing project, the storage format of Jsp files may be UTF-8. If the newly installed eclipse is enabled, the encoding formats used by default are iso8859-1. As a result, Chinese characters in jsp are garbled. This Garbled text is easy to solve. Go to eclipse3.1's preference settings to find general-> edidor and set it to UTF-8 for your file opening. Eclipse will automatically open it again in the new encoding format. The Chinese characters are displayed normally.

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.