JSP and servlet Chinese garbled problem

Source: Internet
Author: User
Tags dreamweaver

everyone in the development process of JSP, often appear in Chinese garbled problem, may one to haunt everyone, now the JSP development encountered in the Chinese garbled problem and the solution to write for everyone to reference. First look at the origin of the Java Chinese issue:

Java's kernel and class files are Unicode-based, which makes Java programs a good cross-platform, but also brings some trouble with Chinese garbled problems. There are two main reasons, the Java and JSP files themselves compile the garbled problem and Java program in other media interaction generated garbled problem. First of all, Java (including JSP) source files are likely to contain Chinese, and Java and JSP source files are saved based on Byte stream, if the Java and JSP compiled into a class file process, the use of encoding and source file encoding inconsistent, there will be garbled. Based on this garbled, it is recommended to try not to write Chinese in the Java file (note Part does not participate in compiling, write Chinese does not matter), if must write, as far as possible manually with parameters-ecoding GBK or-ecoding gb2312 or-ecoding UTF-8 compile; for JSP, Add <%@ page contenttype= "TEXT/HTML;CHARSET=GBK" to the file header%> or

<%@ page contenttype= "text/html;charset=gb2312"%> basically can solve this kind of garbled problem.

Here are some common Chinese garbled problem resolution methods ( in the following example, Ecoding is gb2312, can also be set to Ecoding GBK or ecoding UTF-8):

One, JSP page garbled

This garbled problem is relatively simple, usually the page encoding inconsistency caused by garbled, general novice prone to such problems, the specific sub-two kinds of situations:

Ø not specified using character set encoding

The following display page (display.jsp) appears garbled:

<HTML><HEAD><TITLE>JSP's Chinese processing </title><meta http-equiv= "Content-type" content= "text/html charset=gb2312 ">

This garbled reason is not specified in the page character set encoding, the JSP page appears in the Chinese characters, and the default iso-8859-1 character set, no Chinese characters, the solution: as long as the page begins with the following code to specify the character set encoding, in the JSP page specify the encoding method ( GB2312), and the browser decoding method is set the same, that is, in the first line of the page plus:

<%@ page contenttype= "text/html; charset=gb2312 "%>, you can eliminate garbled.

The full page is as follows:

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


Ø coded character set settings are inconsistent

The following display page (display.jsp) appears garbled:

<%@ page language= "java" pageencoding= "gb2312"%><%@ page contenttype= "Text/html;charset=iso8859-1"%> <HTML><HEAD><TITLE>JSP's Chinese processing </title><meta http-equiv= "Content-type" content= "text/html charset=gb2312 ">


This garbled reason is due to inconsistent page coding, in this example we can see there are three sets of character set, the following are the three places to understand the specific meaning:

The first <%@ page language= "java" pageencoding= "gb2312"%> is encoded in the format of the JSP file. Eclipse will save the file based on this encoded format. and compile the JSP file, including the Chinese characters inside.
The second encoding is the decoding format. Because the file saved as gb2312 is decoded to iso8859-1, so the Chinese must be garbled. That must be the same. And the second place in this line, can not. The default is also the encoding format using ISO8859-1. So if there is no such a line, there will be garbled. Must be consistent.

The third code is to control how the browser is decoded. If the previous decoding is consistent and error-free, this encoding format can be used without setting. Some pages are garbled because the browser cannot determine which encoding format to use. Because the page will sometimes embed the page, causing the browser to confuse the encoding format garbled.

The complete resolution code is as follows:

<%@ page language= "java" pageencoding= "gb2312"%><%@ page contenttype= "text/html;charset= gb2312"%>< HTML><HEAD><TITLE>JSP's Chinese processing </title><meta http-equiv= "Content-type" content= "text/html charset=gb2312 ">

Second, the form is submitted in Chinese garbled

Here is a submission page (submit.jsp) with the following code:

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

Here is the processing page (process.jsp) code:

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

If the submit.jsp submit English characters can be displayed correctly, if you submit the Chinese language will appear garbled. Cause: The browser uses UTF-8 encoding to send the request by default, while UTF-8 and GB2312 encode the characters differently, which makes the unrecognized character appear.

Ø Post Submission Method

Workaround:

A, encoding conversion when accepting parameters

String S=new string (Request.getparameter ("name"). GetBytes ("Iso-8859-1"), "gb2312");

The modified process.jsp code is as follows:

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

If you use this method, each parameter must be transcoded in this way. Very troublesome. But you can actually get the kanji.

B, through the request.secharacterencoding ("gb2312") to the request unified code, the realization of the normal display of Chinese.

The modified process.jsp code is as follows:

<%@ page contenttype= "text/html; charset=gb2312 "%><%request.secharacterencoding (" gb2312 ");%>

If you use this method to accept this parameter of the page does not have to transcode, you can get the Chinese character parameters. But every page needs to execute this sentence.

C, in order to avoid each page to write request.setcharacterencoding ("gb2312"), you can use the filter for all JSP

for encoding processing. is to use the filter in the servlet specification to specify the encoding, the main code is as follows:

Import Java.io.*;import Javax.servlet.Filter; Import Javax.servlet.FilterChain; Import Javax.servlet.FilterConfig; Import javax.servlet.ServletException; Import Javax.servlet.ServletRequest; Import Javax.servlet.ServletResponse; Publicclass Setcharacterencodingfilter implements Filter {protected String encoding =null; publicvoid destroy () { This.encoding =null; } publicvoid Init (Filterconfig filterconfig) throws servletexception{this.encoding = Filterconfig.getinitparameter (" Encoding ");} Publicvoid DoFilter (servletrequest request, servletresponse response, Filterchain chain) throws IOException, servletexception{request.setcharacterencoding (encoding); Response.setcontenttype ("text/html;charset=" +encoding) ; Chain.dofilter (request, Response);}}

The filter is configured in Web. Xml as follows:

<filter><filter-name>SetCharacterEncodingFilter</filter-name><filter-class> Setcharacterencodingfilter</filter-class><init-param><param-name>encoding</param-name> <param-value>gb2312</param-value></init-param></filter><filter-mapping>< filter-name>setcharacterencodingfilter</filter-name><url-pattern>/*</url-pattern></ Filter-mapping>

The modified process.jsp code is as follows:

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


The above method is only effective for post mode submission.

Ø Get Submit Method

If you use get to submit the Chinese language, the page that accepts parameters will also appear garbled, this garbled reason is also tomcat internal encoding format iso8859-1 caused. Tomcat will encode the kanji with the default encoding of GET, append to the URL after encoding, and result in the iso8859-1 parameters being garbled.

Workaround:

A, the first way to use the post-submission method, decoding the accepted characters, and then transcoding.

B, first configure Tomcat under Server.xml Connector node to add usebodyencodingforuri= "true" property configuration, and then add <% in the JSP page Request.secharacterencoding ("gb2312") encodes the encoding format that is set by;%>.

1. The Server.xml configuration in Tomcat is as follows:

<connector port= "8080" protocol= "http/1.1" connectiontimeout= "20000" redirectport= "8443" useBodyEncodingForURI= " True "/>

2. The modified process.jsp code is as follows:

<%@ page contenttype= "text/html; charset=gb2312 "%><%request.secharacterencoding (" gb2312 ");%>

Third, the database connection garbled

This garbled character will make you insert the database of Chinese into garbled, or read out the display is also garbled, the solution is as follows: in the database connection string to add the coded charset

String url= "jdbc:sqlserver://localhost:1433; databasename=mydb;user=sa&password=sa&

useunicode=true&characterencoding=gb2312 ";

and use the following code in the JSP page:

 

Response.setcontenttype ("text/html;charset=gb2312"); Request.setcharacterencoding ("gb2312");

Iv. on the garbled problem of JSP opening in MyEclipse

For an already existing project, the storage format of the JSP file may be utf-8. If the newly installed eclipse is open, the encoding format used by default may be iso8859-1. So the JSP inside the Chinese characters appear garbled. This garbled fish solution is as follows:

A, Myeclispe window-> Preferences Popup Properties

General-> Workspace Set the text file encoding global settings.

B, right-click your project---Properties---Text file encoding project settings

V. About HTML pages opening in Eclipse garbled condition

Since most of the pages are made by Dreamweaver, their storage format differs from Eclipse's recognition.

In this case, create a new JSP in Eclipse and paste it directly from the Dreamweaver copy page content to the JSP.

Six, JSP page through the URL to pass the Chinese parameter garbled problem

In the project, we often encounter the need to pass Chinese characters in the JSP page switch. Example: http://website/test1.jsp?act=add&type= Apple

Ø in general, we seldom directly in the URL to write the parameters in Chinese, such as the example of "Type= Apple" to pass. If this happens, we only need to make a simple conversion on the page where we receive the parameters.

Code test1.jsp: (main section)

<%@ page language= "java" import= "java.util.*" pageencoding= "gb2312"%><%string type = Request.getparameter (" Type "); String result =newstring (type.getbytes ("iso-8859-1"), "gb2312"); Out.println (Result);%>

The more common approach is to encode the Chinese characters in the URL into a character like type=%20d%20b.

Code myjsp1.jsp:

<%@ page language= "java" import= "java.util.*" pageencoding= "gb2312"%><%@ page import= "java.net.*"%><a Href= './myjsp2.jsp?act=<%=urlencoder.encode ("Chinese Very good")%> ' >test</a>

Code myjsp2.jsp:

<%@ page language= "java" import= "java.util.*" pageencoding= "gb2312"%><%@ page import= "java.net.*"%><% String tempval = Urldecoder.decode (request.getparameter ("act")); Out.println (NewString (Tempval.getbytes (" Iso-8859-1 ")," gb2312 ");%>
Servlet jump to JSP after garbled, Resolved: response.response.setCharacterEncoding ("gb2312");



Turn from:
http://blog.csdn.net/aspxuyang/article/details/7770135

JSP and servlet Chinese garbled problem (go)

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.