Javaweb (i) the difference between garbled resolution and forwarding and redirection in a servlet

Source: Internet
Author: User

Objective

In fact, all the contents of the servlet have been introduced, this article to add a bit of garbled and redirect and forwarding the difference between!

One, request parameter garbled problem 1.1, GET request

1) Garbled example

The parameters of the GET request are submitted after the URL, which is in the request line.

  

  

Results:

    

SERVLET_DEMO_0040 is a normal servlet, when the browser accesses it, using GET request to submit a username= xiaoming parameter value, in Doget to get the parameter value, and print to the console, found garbled

2) The reason for garbled appearance

Previous knowledge:

Code table: is a rule, used to let us understand the language into a computer can understand the language of a rule , there are many is0-8859-1,gbk,utf-8,utf-16, such as a series of code tables,

For example, gbk,utf-8,utf-16 can identify a Chinese character, and if you want to identify English, you can use is0-8859-1 and other code tables.

Coding: Convert the language we understand into a language that computers can understand . This process is the function of coding.

Decoding: translating computer-recognized languages into languages we can see . This process is the function of decoding.

Here can only represent after a coding example, some programs will be a Chinese character or a letter with a different code table for several consecutive code, then the first code is the function above, the second code,

Is the computer can recognize the language into the computer can recognize the language (the conversion rules are different), then the decoding process, it must be two times decoding, that is, the inverse process of coding, the following example is a good explanation of the problem:

The browser is using the UTF-8 Code table, through the HTTP protocol transmission, the HTTP protocol only supports IS0-8859-1, to the server, the default is to use the Is0-8859-1 Code table, look at the picture:

    

As you can see from the above figure, there are three processes that have undergone two encodings, so we need to decode them two times:

1) The browser will "Xiao Ming" using UTF-8 Code table encoding (because xiaoming this is a Chinese character, so use can identify the Chinese code table, which we can manually set in the browser, if the use of the Code table can not identify Chinese, then will appear garbled,

Because the code table can not find the corresponding computer symbols in Chinese, it may be used?? and other symbols), the encoding is 1234, and it is transmitted over the HTTP protocol.

2) in the HTTP protocol transmission, can only use the symbols represented in the Iso-8859-1 Code table, so will our original 1234 once again encoded , this time using the iso-8859-1, get???? , and then transfer to the server.

3) The server obtains this data is after two times encodes the data to obtain, therefore must follow the original code the process to decode, first UTF-8 code, then in the Iso-8859-1 code, then the decoding process, must be the first iso-8859-1 decoding, then uses UTF-8 decoding,

This will give you the right data.????. GetBytes ("iso-8859-1");//First decoding, conversion to the computer can recognize the language, new String (1234, "UTF-8");//second decoding, conversion to the language we know

3) Workaround

    

Results:

      

1.2. POST Request

The parameters of the Post request method are in the request body , relative to the GET request is much simpler, there is no HTTP protocol This step of the encoding process, only need on the server side, set the server decoding the Code table with the browser code table is the same as the line ,

Here the browser is using the UTF-8 Code table encoding, then the server-side set to decode the Code table for UTF-8 is OK.

Set server side using UTF-8 Code table decoding:

Request.setcharacterencoding ("UTF-8"); Command Tomcat to decode using the UTF-8 Code table instead of the default iso-8859-1.

So in many cases, the first sentence of the Dopost method is the code that prevents garbled characters when the request parameter is obtained .

Summary request parameter garbled problem:

Get request and POST request way of Chinese garbled problem processing way different

Get: Request parameters in the request line, involving the HTTP protocol, manually solve the garbled problem, know the root cause of garbled, the right remedy, the principle is to do two times encoding, two decoding process

New String (Xxx.getbytes ("iso-8859-1"), "UTF-8");

Post: Request parameters in the request body, using the Servlet API to solve the garbled problem, the principle is to encode once decoding, command Tomcat to use a specific code table decoding.

Request.setcharaterencoding ("UTF-8");

Second, response response back to the browser appears in Chinese garbled

Let's start by describing how the response object sends data to the browser. Two methods, a Getoutputstream, a getwrite:

Servletoutputstream Getoutputstream (); Gets the output byte stream, which provides write () and print () two output methods.

PrintWriter Getwrite (); Gets the output character stream, which provides write () and print () two output methods.

The print () method is used at the bottom of the Write () method, the equivalent of the print () method is the write () method is encapsulated, so that developers more convenient and efficient use, want to output what, directly select the appropriate print () method, Instead of thinking about how to convert bytes.

2.1, Serveltoutputstream Getoutputstream ();

   

Result: Cannot output Chinese directly, direct output Chinese will report abnormal

    

Report abnormal source Code analysis:

    

Workaround:

Resp.getoutputstream (). Write ("hahaha, I want to output to the browser". GetBytes ("UTF-8"));

Will output the Chinese character first with UTF-8 encoding, without having tomcat to encode , so if the browser with a UTF-8 code table for decoding, then the correct output, if the browser is not UTF-8, then there will be garbled,

So that's the key to see what the browser's code table, this is not very good, it is also important to note, is to use the Write (byte) method, because the print () method does not output a byte type method.

Test: Because I'm using Google Chrome, it uses GB2312 by default, so here's the GB2312.

      

      

2.2, PrintWriter Getwrite ();

The direct output of Chinese, will not be reported abnormal, but certainly will be reported abnormal, because the code table with ISO-8859-1 can not identify Chinese, the beginning is wrong, how to decode the code read useless.

There are three ways to correctly output Chinese:

1) using the servlet API response.setcharacterencoding ()

Response.setcharacterencoding ("UTF-8"); Let Tomcat encode the Chinese with UTF-8 that we want to respond to the browser, instead of using the default iso-8859-1, depending on whether the browser is using a UTF-8 code table that is as flawed as the one above.

Test: Because I'm using Google Chrome, it uses GB2312 by default, so here's the GB2312.

     

2) notify both Tomcat and browser to use the same Code table

Response.setheader ("Content-type", "text/html;charset=uft-8"); Manually set the response content to notify Tomcat and the browser to use Utf-8 for encoding and decoding.

Charset=uft-8 is equivalent to response.setcharacterencoding ("UTF-8");//notify Tomcat to encode using Utf-8

Response.setheader ("Content-type", "text/html;charset=uft-8");//combine to notify Tomcat with Utf-8 encoding, and notify the browser to decode with UTF-8.

Response.setcontenttype ("text/html;charset=uft-8"); using the servlet API to notify Tomcat and force the browser to encode and decode using UTF-8, the underlying code is the code on the previous line, which is simply encapsulated .

      

3) Notify Tomcat, in the use of Html<meta> notification browser (HTML source code), note:<meta> suggested that the browser should use the encoding, can not force the request

    

So response in response, just notify Tomcat and browser to use the same Code table, generally use the second method, then you can solve the problem of garbled response

Three, the summary request and the response garbled 3.1, the request garbled

GET Request:

It's been coded two times, so we're going to decode it two times.

First decode: Xxx.getbytes ("iso-8859-1"); get yyy

Second decoding: New String (yyy, "utf-8");

Continuous write: New String (Xxx.getbytes ("iso-8859-1"), "UTF-8");

POST request:

Once encoded, so it is only once decoded, using the servlet API request.setcharacterencoding ();

Request.setcharacterencoding ("UTF-8"); Not necessarily solve, depending on what the browser is using the Code table to encode, browser with UTF-8, then write UTF-8 here.

3.2, Response garbled

Getoutputstream ();:

Using this byte output stream, can not directly output Chinese, will be abnormal, to output Chinese, the workaround is as follows

Resolution: Getoutputstream (). Write (Xxx.getbytes ("UTF-8")); Manual Chinese with UTF-8 Code table encoding, into a byte transfer, into a byte, will not be reported abnormal, and Tomcat will not be encoded, because it has been encoded, so to the browser,

If the browser is using UTF-8 Code table decoding, then there will be no Chinese garbled, on the contrary, there are Chinese garbled, so this method, can not fully guarantee that the Chinese is not garbled

Getwrite ();:

Using the character output stream, can output Chinese directly, will not be abnormal, but will appear garbled. Can be solved in three ways, always using the second method

Workaround: Notify Tomcat and the browser to use the same Code table.

   Response.setcontenttype ("Text/html;charset=utf-8"); Notifies the browser to use UTF-8 decoding

Notifies Tomcat and the browser to use UTF-8 encoding and decoding. The underlying principle of this method is this sentence: Response.setheader ("ContentType", "text/html;charset=utf-8");

Note: Boththe Getoutputstream () and Getwrite () methods cannot be used at the same time, only one can be used at a time, or an exception is reported    

Iv. differences between requests and forwards in Servlets 4.1. How to use

1) Call forward, redirect statements in the servlet as follows:

Request.getrequestdispatcher ("new.jsp"// forwarding to new.jsp Response.sendredirect ("new.jsp"// redirect to new.jsp

2) in the JSP page you will also see the following way to implement the forwarding:

<jsp:forward page="apage.jsp" />

Of course, you can also implement redirects in the JSP page:

<%response.sendredirect ("new.jsp"// redirect to new.jsp

Example:

//Get username InformationString Username=request.getparameter ("username"); //Forwarding and redirection if(Username.equals ("Admin")){  //Prompt user already exists, cannot registerRequest.setattribute ("message","the user is already present and cannot be registered");//To add a hint message, you need to show it in the usercreate.jsp pageRequest.getrequestdispatcher ("usercreate.jsp"). Forward (request, response);//Transfer Method}Else{  //Prompt for registration successRequest.setattribute ("message","Registration Successful"); Response.sendredirect ("indext.jsp");// redirect}
4.2. Difference: Redirect and forward workflow

  

1) Forwarding Workflow '

The first step: the client browser sends an HTTP request
Step two: The Web server accepts this request
Step three: Call inside a method to complete the request processing and forwarding actions inside the container
The fourth step: Send the target resource to the customer; here, the forwarded path must be a URL under the same Web container, which cannot be redirected to another Web path, passing in the request within its own container. In the client browser path bar, the path to the first access is still displayed.
In other words, the customer does not feel the server to do the forwarding. The forwarding behavior is that the browser makes only one access request .

2) Redirection workflow

    

The first step: the client browser sends an HTTP request
The second step: the Web server to Send 302 status Code response and corresponding to the new location to the client browser
Step three: Customer browser Discovery is a 302 response, then automatically send a new HTTP request, the request URL is the new location address
Fourth step: The server looks for resources and sends them to customers based on this request. Here the location can be redirected to any URL, since the browser has re-issued the request, there is no concept of request delivery.
The client browser path bar displays its redirected path, and the customer can observe the change of address. The redirect behavior is that the browser has made at least two access requests .

Summary: One sentence, forwarding is the server behavior, redirection is the client behavior .

4.3. Difference: Number of requests

1) redirect

Redirect, in fact, is two times request

For the first time, the client request A, the server responds, and response back, telling the browser that you should go to B. This time, IE can see the address has changed, and the history of the fallback button is also lit. Redirects can access resources other than their own web apps. During the redirection process, the transmitted information is lost .

Example:

Response.sendredirect ("loginsuccess.jsp");

2) forwarding

Forwarding is a request

Request forwarding is the processing power of a request/response within the server, handed over to another

For the client, it knows only the one that was requested first, not the middle B, or even C, D. The transmitted information is not lost .

RequestDispatcher dis=request.getrequestdispatcher ("loginsuccess.jsp");       Dis.forward (request,response);
4.4. Examples in life illustrate the difference

  

Let's say you go to a license.
Redirect: You go to a bureau first, the people of a bureau said: "This matter does not belong to our management, to the B-Bureau", then, you have to withdraw from a, you take the bus to the B bureau.
Forwarding: You first went to a bureau, a after watching, know that this thing should actually B to tube, but he did not put you back, but let you sit for a while, oneself to the back office contact B's people, let them do well, sent over.

V. Summarize the differences between requests and forwards in a servlet

1) REDIRECT execution: The Web server sends an HTTP response to the browser-the browser accepts this response and sends a new HTTP request to the server-the server looks for resources and sends them to the browser based on this request. It can be redirected to any URL and cannot share data within the request scope .
2) redirection is done on the client side, and the page is turned by the new address .
3) redirection is through the browser re-request address, in the address bar can display the post-turn address .
4) Forwarding process: The Web server calls the internal method to complete the request and forward actionwithin the container--"sends the target resource to the browser, which can only be used in the same web app, sharing data within the request scope .
5) forwarding is performed on the server side, and the commit information is passed across multiple pages through the forward () method .
6) forwarding is the transfer of control within the service, and the address bar of the client browser does not show the post-turn address.

Like on the point of a "recommendation" Oh!

Javaweb (i) the difference between garbled resolution and forwarding and redirection in a servlet

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.