There are many solutions to deal with character encoding on the Internet, and here, I stand on the shoulders of predecessors to make their own summary.
In my opinion, the solution to the problem of garbled characters is to encode the settings in 3 places:
1.HTML, JSP and other front-end pages;
2. Request and response objects in the background servlet;
3. server configuration file.
1.HTML, JSP, such as front-end page, the code first look at the front page of the META tag is correctly set the code, this meta tag is the head of the page
<%@ Page Language="Java"Import="java.util.*"pageencoding="Utf-8"%>
2. Settings for request and response in the background
2-1. When a URL request is received in the background, if the request is not encoded, then the received request content will be garbled, then there are two scenarios to consider:
2-1-1. If it is a GET request, first get the parameters in the URL request, for example:
String method = Request.getparameter ("method");
The string object is then called to complete the conversion of the parameter encoding,
New
Here the string is constructed with two parameters: convert the argument from a string to a character array as the first argument, and the second argument is the encoding of the converted string.
2-1-2. If it is a POST request, just precede the request parameter with a code that sets the encoding, that is, the Setcharacterencoding method that invokes the set encoding of the request object:
Request.setcharacterencoding ("UTF-8");
2.2. When the background completes the business logic and persistent operation, it may be necessary to output the response stream data to the foreground, if the output content contains Chinese, you need to set the encoding of the response object, you can directly call the Response object setContentType method:
Response.setcontenttype ("Text/html;charset=utf-8");
3. Settings for the server configuration file
After the current two-step setup is still not working, it should also be in the server's installation directory under the Conf folder, such as my E:\tomcat7.0\conf, find the server configuration file Server.xml settings:
<connector connectiontimeout= "20000" port= "8080" protocol= "http/1.1" redirectport= "8443" URIEncoding= "UTF-8"/ >
The processing of character encoding garbled in Java EE development