Solve the problem of JSP Chinese garbled characters

Source: Internet
Author: User

1. Resolve garbled characters in the response first

What is garbled in the response? Change the "username" in the page to "user name" and you'll know.

The so-called response in the garbled, is to display the page garbled, because the page data is put in response from the server side (response), and then sent to the browser, if the response data can not be parsed correctly, there will be garbled problems.

Why is there no problem in English? Because in iso-8859-1,gb2312, Utf-8 and any one encoding format, the English encoding format is the same, each character occupies 8 bits, and the Chinese is troublesome, in the gb2312 the next Chinese accounted for 16 bits, two bytes, and in Utf-8 the next Chinese to occupy 24 bits, three bytes. When the browser does not know how to determine the encoding, the characters will be truncated from the middle, and then the display will be confused. So, to solve the garbled problem, is to tell the browser what kind of encoding we are using.

In order to get the normal display of Chinese, note the following steps:

  1. Since the server first reads the JSP file locally and then writes the response after processing, we first need to know the encoding format of the JSP file. Solve the problem from the source.

    Under the WINDOWXP we use, the file default encoding format is gb2312.

  2. We want to add the encoded information in the HTTP response (response), using the following method:

    <%@ page contenttype="text/html; charset=gb2312"%>

    This section is placed on the first line of the JSP page, to specify the type of response and encoding format, contenttype to text/html is the HTML content, CharSet represents the encoding gb2312. This allows the browser to get the encoding format from the response.

    This form of <%@%> is called the JSP Directive (Directive), which now touches the page directive.

  3. You also need to specify the encoding format in HTML
    "content-type" content="text/html; charset=gb2312" />    <title>title</title>

    The meta section is used to specify the encoding format of the current HTML, note that this paragraph should be placed in the head tag and placed at the front of the head tag, if not the front of the first IE may cause problems, especially in the title of the case of Chinese.

    After completing the above three-paragraph test, we can guarantee that the output JSP page will display Chinese correctly.

    2. Post garbled

    First add the form to the method= "post", let the form submitted by using the Post method.

    When sending a request, the encoding used is iso-8859-1, which means that only English is a valid character, this restriction is because the members of the HTTP standard originally specified are from English-speaking countries, so if you use the default way to obtain data from the request, Chinese will all become garbled.

    If you do not believe, you can enter Chinese in the example just now, then submit:

    The results of the submission will look like this:

    How to solve it? We want to prefix the JSP with a Java statement that sets the character encoding of the request.
    <%    request.setcharacterencoding ("gb2312"); %>

    As a result, those garbled characters are normal:

    3. Get garbledWarning

    Get case, using UrlEncode () does solve garbled problems, which needs to be supplemented.

    By clicking the hyperlink directly, the default submission method for form is get. The solution in post mode is simple, because the data submitted in post mode is appended to the body portion of the HTTP request in binary mode, and it is only sufficient to specify the encoding format in the background. The Get method appends parameters directly to the URL, which cannot be processed using request.setcharacterencoding (), and the result is that all Chinese in the Get form is garbled.

    There is no easy way to do this, only one of these Chinese can be converted, using the new String (bytes, "gb2312") for transcoding.

    There is no easy way to do this, only one of these Chinese can be converted, using the new String (bytes, "gb2312") for transcoding.

    <% String username = request.getparameter ("username"); byte[] bytes = username.getbytes ("iso-8859-1"); string result = new String (bytes, "gb2312"); Out.print (result); %>

    As we can see, we first get the parameters from request, then break the string into byte array according to ISO-8859-1 encoding, then use the GB2312 encoding group to synthesize the new string, and finally print out the normal Chinese.

    Written together, it becomes:

    <%=new string (New String (Request.getparameter ("username"). GetBytes ("Iso-8859-1"), "gb2312")%>            

    The disadvantage of this is that all the Chinese that are obtained from the request need to be transcoded, very cumbersome.

    This solves the Chinese garbled question is too cumbersome, does the general test example also can, does the large-scale project to be very troublesome, therefore generally uses the filter to solve. Under the spring framework. Example 1

     <!--Spring's character filter, not required, can be resolved in other ways-<filter> <FILTER-NAME>CHARACTERENCODINGFILTER&L t;/filter-name> <filter-class  > Org.springframework.web.filter.characterencodingfilter</filter-class  > <init-param> <param-name>encoding</param-name> <param-value>utf-            8  </param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true  & lt;/param-value> </init-param> </filter> <filter-mapping> <filter-name> ; characterencodingfilter</filter-name> <url-pattern>/*  </url-pattern> </filter-mapping>  

    Example 2 We can customize a filter to solve the problem of Chinese garbled

    1 Importjava.io.IOException;2 ImportJavax.servlet.Filter;3 ImportJavax.servlet.FilterChain;4 ImportJavax.servlet.FilterConfig;5 Importjavax.servlet.ServletException;6 Importjavax.servlet.ServletRequest;7 ImportJavax.servlet.ServletResponse;8 9  Public classEncodingfilterImplementsFilter {Ten  One      Public voidInit (filterconfig config)throwsservletexception {} A  -      Public voiddestroy () {} -  the      Public voidDoFilter (servletrequest request, - servletresponse Response, - filterchain chain) -             throwsIOException, servletexception { +  -Request.setcharacterencoding ("gb2312"); + Chain.dofilter (request, response); A     } at  -}
    View Code

    The filter interface is implemented in this encodingfilter, and the three methods defined in the filter interface are implemented in Encodingfilter, where Dofilter () Code to implement the main function: Set GB2312 encoding for the request and perform chain.dofilter () to continue with the following operation.

    Similar to a servlet, it needs to be configured in Web. XML in order for the filter to work.

    <filter>    <filter-name>EncodingFilter</filter-name>    <filter-class>anni. Encodingfilter</filter-class></filter><filter-mapping>    <filter-name>encodingfilter </filter-name>    <url-pattern>/*</url-pattern></filter-mapping>        

    The filter label section defines the filters used, and the filter-mapping tag tells the server which requests to be processed by the filter. The/* Here indicates all requests,/represents the root path, * (asterisk) represents all requests, and together it becomes all requests under the root path.

    In this way, all requests are intercepted by Encodingfilter and the specified gb2312 encoding is set on the request.

Solve the problem of JSP Chinese garbled characters

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.