Chinese garbage problem in javaWeb

  Garbage problem can be divided response garbled and request garbled. request garbage problem include ( GET request garbled and post requests garbled ).

  •   response to solve the garbage problem
. 1  // the setContentType () needs to be set before the getWriter () Method 
2 the response.setContentType ( "text / HTML, charset = UTF-. 8"); // Set the browser in response Content-Type header is text / html; charset = utf-8 encoded. 
. 3 the PrintWriter OUT = response.getWriter ();
 . 4 out.write ( "Chinese output");
  •  garbled request (get request distortion)
. 1  // form submission form submit get class content are in the url
 2  // Tomcat default ISO-8859-1 is a need to add the server.xml under conf tomcat URIEncoding = "UTF-8" as follows. 
. 3 <Connector Port = "8080" Protocol = "the HTTP / 1.1"
 . 4                 connectionTimeout = "20000"
 . 5                 the redirectPort = "8443" the URIEncoding = "UTF-. 8" /> 
// if you modify only a few Chinese words can use
new String (request.getParameter ( "xxx"). getBytes ( "ISO-8859-1"), "UTF-8") to solve the garbage problem.
  •  request distortion (distortion POST request)
// POST request REQUEST request submitted content thereof is positioned so that rather than url requests and get different treatments 
Request.setCharacterEncoding ( "UTF-. 8" ); 
String name = request.getParameter ( "name" ); 
System.out.println ( name); // output is Chinese

  In javaWeb project post request distortion filter is generally used to resolve. spring provides org.springframework.web.filter.CharacterEncodingFilter solve the garbage problem submit post. Used as follows:

1      <! - add the following in web.xml -> 2      < filter > 
. 3          < filter-name > EncodingFilter </ filter-name > 
. 4          < filter-class > org.springframework.web.filter.CharacterEncodingFilter < / filter-class > 
. 5          < the init-param > 
. 6              < param-name > encoding </ param-name > 
. 7              < param-value > UTF-. 8 </ param-value > <-! encoded to request the set encoded as UTF -8-->
8          </init-param>
 9         <init-param>
10             <param-name>forceEncoding</param-name>
11             <param-value>true</param-value>
12         </init-param>
13     </filter>
    <!-- 设置 filter-mapping -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

 

 

Guess you like

Origin www.cnblogs.com/dengsheng/p/11121686.html