How to solve the garbled problem in Java Web Applications

Source: Internet
Author: User


This work is licensed using the "knowledge sharing signature"-"non-commercial use"-2.5 mainland China License Agreement in the same way.

 

 

When we browse the Web page from the perspective of Java programmers, we will find that: on the one hand, the client browser (ie or Firefox) submit an HTTP request in form or link mode and process the response data sent by the HTTP server) display it to users in an appropriate way. On the other hand, on the Java Web application server, an HTTP request can be processed by a servlet class or a JSP webpage. The request data comes from httpservletrequest, and the response data is sent to httpservletresponse. The entire HTTP request process is composed of four steps: client request submission, server-side request processing, server-side response data returned, and user-side response data processing. Data is encoded or decoded in the specified encoding mode during transmission. If not properly handled, garbled characters may occur.

Client Processing

When the client sends an HTTP request, data in the following format is sent to the server:

<Request-line>
<Headers>
<CRLF>
[<Request-body> <CRLF>]

For more information about the HTTP request format, refer to the HTTP protocol and HTML form (let's talk about the difference between get and post.
Request-line and request-body must be encoded accordingly.

Request-line encoding

The URL section in request-line must beApplication/X-WWW-form-urlencodedEncoding method. The character set used for encoding is the character set used when the current web page is displayed in a browser.

JDK has two classes for processing data of the application/X-WWW-form-urlencoded type: urlencoder and urldecoder. When the data on the webpage needs to be manually urlencoding, you can use the urlencoder class to complete encoding. The locations for manual urlencoding processing include:

  • Link (<A> </a>;
  • The action label attribute in the form (<form> </form>) submitted in post mode.

For example, such a link should not be generated on a webpage:

<! -- Incorrect syntax --> <br/> <a href = "/Hello/checkuser.html? Opt = Chinese> User Authentication "</a>

The correct statement is as follows:

<! -- Results of urlencoding using the UTF-8 character set --> <br/> <a href = "/Hello/checkuser.html? Opt = % E4 % B8 % ad % E6 % 96% 87 "> User Authentication </a>

To this end, one of the solutions can use the scripting language for urlencoding processing on the JSP webpage. For example:

<% @ Page import = "java.net. urlencoder" %> <br/> <a href = "/Hello/checkuser.html? Opt = <% = urlencoder. encode ("Chinese", "UTF-8") %> "> User Authentication </a>

Request-body Encoding

Request-body is generated only when post is submitted. The request-body encoding method is specified by the form's enctype tag attribute, same as request-line, the character set used for encoding request-body is also the character set used when the current webpage is displayed in the browser. The request-body encoding process is automatically completed by the client browser without additional programming.

Server Processing

Compared with the client, the server provides two methods to process request data when receiving HTTP requests: automatic processing and no processing.
Generally, the server automatically processes data of the application/X-WWW-form-urlencoded type (including data in request-line and request-body) and Servlet (servlet or JSP webpage) you can use getparameter () or getparametervalues () of the request object to obtain the data. For other mime-type data, the HTTP server directly submits the processing process to the servlet (servlet or JSP webpage) that corresponds to the HTTP request.
For example, the user side has the following forms submitted:

<Form action = "checkuser.html? Opt = xxx "method =" Post "> <br/> <input type =" text "name =" username "value =" yyy "/> <br/> <input type = "text" name = "username" value = "Zzz"/> <br/> <inupt type = "Submit" value = "Submit"/> <br/> </ form>

When a table is submitted, the servlet (servlet type or JSP page) corresponding to checkuser.html can be obtained through the following method after the server automatically processes the table:

String opt = request. getparameter ("Opt"); <br/> string [] users = request. getparametervalues ("username ");

By default, the server performs urldecoding for the ISO-8859-1 character set for the received application/X-WWW-form-urlencoded type data, and the processed string inner code is the ISO-8859-1. For HTTP servers without any additional settings, our servlet must perform corresponding decoding after obtaining data to generate a string with an internal code of UTF-16 (UNICODE.
For example, for urlencoding data in the UTF-8 character set in the client request data, the servlet needs to perform the following decoding:

String opt = request. getparameter ("Opt"); <br/> If (OPT! = NULL &&! "". Equals (OPT) {<br/> opt = new string (OPT. getbytes ("ISO-8859-1"), "UTF-8"); <br/>}

To avoid this extra encoding/decoding, that is to say, let the server know the character set used by the user in urlencoding, and then directly perform urldecoding for the corresponding character set, different HTTP servers provide different solutions.
Take Tomcat as an example. Tomcat's automatic request-line decoding method is specified by the tomcat configuration file server. xml. In server. the connector tag in XML provides the uriencoding tag attribute. You only need to specify the character set for decoding, tomcat will automatically decode the data processed by application/X-WWW-form-urlencoded in request-line. For example:

<Connector connectiontimeout = "40000" Port = "8080" protocol = "HTTP/1.1"
Uriencoding = "UTF-8" redirectport = "8443"/>

Tomcat automatically decodes the request-body by setting the characterencoding value of the request. For example:

Request. setcharacterencoding ("UTF-8 ");

However, this operation must be completed in the filter in advance. Using this method in servlet does not work anymore. An example of filter is as follows:

Import Java. io. ioexception; <br/> Import javax. servlet. filter; <br/> Import javax. servlet. filterchain; <br/> Import javax. servlet. filterconfig; <br/> Import javax. servlet. servletexception; <br/> Import javax. servlet. servletrequest; <br/> Import javax. servlet. servletresponse; </P> <p> public class characterencodingfilter implements filter {</P> <p> private string encoding; </P> <p> Public characterencodingfilter () {<br/> encoding = NULL; <br/>}</P> <p> Public void destroy () {<br/> encoding = NULL; <br/>}</P> <p> Public void dofilter (servletrequest request, servletresponse response, <br/> filterchain chain) throws ioexception, servletexception {</P> <p> request. setcharacterencoding (encoding); <br/> chain. dofilter (request, response); <br/>}</P> <p> Public void Init (filterconfig) throws servletexception {</P> <p> encoding = filterconfig. getinitparameter ("encoding"); <br/> If (encoding = NULL | "". equals (encoding) {</P> <p> encoding = "UTF-8"; <br/>}< br/>}

We can use this filter in Web. xml. The configuration of Web. XML is as follows:

<Filter> <br/> <filter-Name> character encoding filter </filter-Name> <br/> <filter-class> <br/> characterencodingfilter <br/> </filter-class> <br/> <init-param> <br/> <param-Name> encoding </param-Name> <br/> <param-value> UTF-8 </param-value> <br/> </init-param> <br/> </filter> <br/> <filter-mapping> <br/> <filter- name> character encoding filter </filter-Name> <br/> <URL-pattern>/* </url-pattern> <br/> </filter-mapping>

Through the preprocessing of the two methods, the data retrieved in servlet can be directly used without ISO-8859-1 decoding.

Character Set Selection

When processing data of the application/X-WWW-form-urlencoded type, you need to pay attention to the character set selection problem. As mentioned above, whether it is request-line or request-body, the urlencoding character set is the character set used when the current webpage is displayed on the browser. This information is provided in the HTTP response when the HTTP server generates an HTML webpage.
When the HTTP server receives an HTTP request, the server always needs to send an HTTP Response to the client. The format of the HTTP response data is the same as that of the HTTP request data. It consists of the following parts:

<Response-line>
<Headers>
<CRLF>
[<Response-body> <CRLF>]

The following describes the server response information when requesting an HTML webpage:

HTTP/1.1 200 OK
Server: APACHE-Coyote/1.1
Content-Type: text/html; charset = UTF-8
Content-Length: 265
Date: Thu, 17 Dec 2009 05:20:36 GMT

 

<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> test </title>
</Head>
<Body>
<H1> Hello World
</Body>
</Html>
[End]

The Content-Type of headers specifies the data format of the data stream and the character set used for display. This indicator can be specified in the following ways:
1. html webpage
Multiple <META/> tags exist in

<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">

2. jsp webpage
In addition to the <META/> tag, you also need to set the following code in the JSP webpage header:

<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8" pageencoding = "UTF-8" %>

3. servlet class
If you want to transmit HTML data to the user through response in the servlet class, you must specify Content-Type before transmission. The Code is as follows:

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

The preceding three methods ensure that the browser uses the correct decoding method and character set to display the content when the response data is transmitted to the client browser.

Conclusion

In short, content-type is the link between the client and the server. Through this indicator, both parties can correctly encode and decode the relevant data. As long as you understand the role and usage of Content-Type, The garbled problem will be solved.

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.