A Conversion Method for Java/jsp garbled characters
In fact, many people are confused about Garbled text. There are also manyArticleThis section describes how to handle Garbled text.
Many people try to solve the problem after finding garbled code on the Internet. There is usually no right remedy.
In JSP, my knowledge is weak. Currently, I only know that Chinese characters are garbled for three reasons. Find the cause to remedy the problem.
1. Set the contenttype of JSP
<% @ Page contenttype = "text/html; charset = gb2312" %>
2. Some classes in some packages do not have good support for Chinese. For example, in the uploaded package I just used, the classes in this package do not support Chinese. All Chinese characters displayed on the webpage are ???????. Later, the new string (file_item.getname (). getbytes ("iso8859-1"), "GBK") was used to solve the problem.
For example:
<% @ Page contenttype = "text/html; charset = GBK" Language = "Java" Import = "Java. SQL. *" errorpage = "" %>
<% @ Page import = "org. Apache. commons. fileupload. diskfileupload, org. Apache. commons. fileupload. fileitem" %>
<%
If ("Post". inclusignorecase (request. getmethod () & request. getcontenttype (). startswith ("multipart/form-Data ")){
Diskfileupload upload = new diskfileupload ();
Java. util. List Files = upload. parserequest (request); // obtain the form
Fileitem file_item;
For (INT I = 0; I <files. Size (); I ++) {// cyclically obtain the elements in the form. Here we can check whether the ID has a value for dbms_phsgame.
File_item = (fileitem) files. Get (I );
// If an ID element exists, retrieve dbms_phsgame from the database.
If ("File". inclusignorecase (file_item.getfieldname ())){
Out. println (new string (file_item.getname (). getbytes ("iso8859-1"), "GBK "));
}
}
}
%>
<HTML>
<Body>
<Form name = "form1" enctype = "multipart/form-Data" method = "Post" Action = "">
<Input type = "file" name = "file">
<Input type = "Submit" name = "Submit" value = "Submit">
</Form>
</Body>
</Html>
3. database data is garbled.
Here is a recommended method --- getbytes ().
// Changed from iso8859-1 to GBK when reading the database
Public String gbkconverter (string s_string ){
Try {
String des = new string (s_string.getbytes ("iso8859-1"), "GBK ");
Return des;
}
Catch (exception ex ){
String des = "";
Return des;
}
}
// Process the processing of the Chinese data generated in the page when writing the database, from GBK to iso8859-1
Public String isoconverter (string s_string ){
Try {
String des = new string (s_string.getbytes ("GBK"), "iso8859-1 ");
Return des;
}
Catch (exception ex ){
String des = "";
Return des
}
}
BTW:
<% @ Page contenttype = "text/html; charset = gb2312" %>
Yes, and it must be in the first line of the file (not in the include file)
Also, if the form content cannot be correctly parsed, add the following sentence:
Request. setcharacterencoding ("gb2312 ");