When writing Chinese characters in the JSP input box to the background, garbled characters often occur:
Today, I read a video from instructor Han shunping, got a preliminary understanding of the Garbled text, and wrote it out through my own practices.
Cause of garbled characters: When java is transmitted on the network, it is transmitted in the form of iso-8859-1 encoding. Therefore, when encoding and decoding (to obtain the passed value), it is necessary to match ..
There are three solutions:
1. transcode new String (u. getBytes ("iso-8859-1"), "gb2312 ");
2. Use a filter to solve [instability]
3. [unstable] by configuring the server. xml file
Example:
String userName = requset. getParameter ("userName ");
UserName = new String (userName. getBytes ("iso-8859-1"), "gb2312 ");
However, it is still too troublesome to perform this operation every time. Therefore, you can write a tool class to convert garbled characters into gb2312.
Public class Tools {
// Provides a method to convert garbled characters into gb2312
Public static String getNewString (String input ){
String result = "";
Try {
Result = new String (input. getBytes ("iso-8859-1"), "gb2312 ");
} Catch (Exception e ){
E. printStackTrace ();
}
Return result;
}
In use,
String userName = request. getParameter ("userName ");
UserName = Tools. getNewString (u );
Note: When this method is used, it is not necessarily followed by gb2312, which may be gbk or UTF-8. The specific encoding of the page that transmits values to the controller depends on the encoding.
For example, in my login. jsp, is <% @ page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>, so I have to use
Id = new String (id. getBytes ("iso-8859-1"), "UTF-8"); now... You cannot make a copy.
The third method: Instructor Han only said that this method can solve the problem. It failed to pass the test, and I failed to pass the test. It may be related to the tomcat version.
In the tomcat configuration file server. xml,
<Connector port = "8080" protocol = "HTTP/1.1"
ConnectionTimeout = "20000"
RedirectPort = "8443" type = "regxph" text = "yourobjectname"/>
Add an attribute URIEncoding = "GBK"