Common solutions to Servlet Chinese garbled characters

Source: Internet
Author: User

Common solutions to Servlet Chinese garbled characters
An error occurs on the servlet page. The print is garbled, why?
Public class toDetail extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {

Response. setContentType ("text/html ");
Response. setCharacterEncoding ("UTF-8 ");
PrintWriter out = response. getWriter ();
 
Int id = Integer. parseInt (request. getParameter ("ID "));
GoodsBeanAction gba = new goodsBeanAction ();
GoodsBean gb = gba. getGoodsBean (id );
Request. setAttribute ("goodsInfo", gb );
Request. getRequestDispatcher ("showDetail. jsp tutorial"). forward (request, response );
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
This. doGet (request, response );
}

}

Best Answer

Can you enter Chinese characters for your ID attribute? If yes, you need to set the character encoding before receiving the parameter, request. setCharacterEncoding ("gbk");, there is a response. setContentType ("text/html; charset = gbk ");

The details are as follows:

1. The CHARSET in JSP should be GB2312
ContentType = "text/html; charset = GB2312"

2. The SERVERLET class must contain
Request. setCharacterEncoding (gb2312 );

3. reformat the character set
The encode and decode corresponding to java.net. URLDecoder are decoded.
When data is transmitted, the browser automatically performs url encoding on the data to be transmitted through the form. The encoding method depends on the encoding method used when the current webpage is displayed.
For the parameters after the url address of the http request message, the encoding method adopted by getparameter and other methods for automatic url Decoding depends on the servlet engine; tomcat uses the ISO8859-1 for decoding by default.
The reformat statement is as follows:
String str1 = new String (request. getParameter ("name"). getBytes ("ISO-8859-1"), "gb2312 ");

4. There are about 92 lines in SERVER. XML in the CONF folder of TOMCAT. (If you haven't changed it)
Find the connector block and add the following line:
URIEncoding = "GBK" or URIEncoding = "GB2312" or URIEncoding = "UTF-8"
 
The complete information should be as follows:
<Connector
Port = "80" maxThreads = "150" minSpareThreads = "25" maxSpareThreads = "75"
EnableLookups tutorial = "false" redirectPort = "8443" acceptCount = "100"
Debug = "0" connectionTimeout = "20000"
DisableUploadTimeout = "true"
URIEncoding = "GB2312"
/>

5. Add the following code between the <servlet> </servlet> labels of the web. xml file in the conf folder of Tomcat
<Init-param>
<Param-name> encoding </param-name>
<Param-value> GB2312 </param-value>
</Init-param>

6. Specify the encoding using the transfer handler in the Servlet specification
<1>. When creating a new servlet, Interfaces interface: inherits javax. servlet. Filter
In options, select: create Inherited Methods; create Constructors;
After it is created, in its doFilter () method:
Arg0.setCharacterEncoding ("gb2312"); // garbled request processing
Arg1.setCharacterEncoding ("gb2312"); // handle garbled response
Arg2.doFilter (arg0, arg1); // continue to execute other filters or jsp, servlet
<2>. In web. xml, change the <servlet> </servlet> Of the servlet filter content to <filter> </filter>.
Modify <url-patterm>/* </url-patterm> in <filter-mapping> </filter-mapping>. "/*" indicates that any file is executed.
 
Introduction filter:
A. Each filter is configured separately in web. xml:
<Filter>
<Filter-name> filter alias </filtr-name>
<Filter-class> physical address of the filter, with the complete package path </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> filter alias </filter-name>
<Filter-patterm> filter access path </filter-patterm>
</Filter-mapping>
B. If you want to delete a servlet class for some reason, the deleted servlet class record will be retained in web. xml,
Therefore, you must manually delete the deleted servlet class information in web. xml.
 
The typical configuration and main code of the filter in web. xml are as follows:

Web. xml:
<Filter>
<Filter-name> CharacterEncodingFilter </filter-name>
<Filter-class> net. vschool. web. CharacterEncodingFilter </filter-class>
<Init-param>
<Param-name> encoding </param-name>
<Param-value> GBK </param-value>
</Init-param>
</Filter>
<Filter-mapping>
<Filter-name> CharacterEncodingFilter </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>
CharacterEncodingFilter. java:
 
Import java. io. IOException;
Import javax. servlet. Filter;
Import javax. servlet. FilterChain;
Import javax. servlet. FilterConfig;
Import javax. servlet. ServletException;
Import javax. servlet. ServletRequest;
Import javax. servlet. ServletResponse;
Public class CharacterEncodingFilter implements Filter
{
Protected String encoding = null;
Public void init (FilterConfig filterConfig) throws ServletException
{
This. encoding = filterConfig. getInitParameter ("encoding ");
}
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
Request. setCharacterEncoding (encoding );
Response. setContentType ("text/html; charset =" + encoding );
Chain. doFilter (request, response );
}
}

7. Solve the garbled characters in the database tutorial
Specify the character set in jdbc. url (not applicable to sqlserver)
When connecting to the database: con = DriverManager. getConnection (url, "sa ","");
Url = "jdbc: Protocol: Sub-Protocol: // IP: port; library? UseUnicode = true & characterEncoding = gb2312 ";


The filter is not enough.
Public class Filter1 implements Filter {
Private FilterConfig _ filterConfig = null;

Public void init (FilterConfig filterConfig) throws ServletException {
_ FilterConfig = filterConfig;
}

Public void destroy (){
_ FilterConfig = null;
}

Public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {chain. doFilter (request, response );
Request. setCharacterEncoding ("gbk ");
Response. setCharacterEncoding ("gbk ");
}
}
In web. xml

<? Xml version = '1. 0' encoding = 'gbk'?>
<Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version = "2.4" xmlns = "http://java.sun.com/xml/ns/j2ee">
<Description> Empty web. xml file for Web Application </description>
<Filter>
<Filter-name> Filter1 </filter-name>
<Filter-class> project1.Filter1 </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> Filter1 </filter-name>
<Url-pattern> *. * </url-pattern>
</Filter-mapping>
<Session-config>
<Session-timeout> 35 </session-timeout>
</Session-config>
<Mime-mapping>
<Extension> html </extension>
<Mime-type> text/html </mime-type>
</Mime-mapping>
<Mime-mapping>
<Extension> txt </extension>
<Mime-type> text/plain </mime-type>
</Mime-mapping>
</Web-app>

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.