The way servlets handle scrambled code in Java

  • 2020-04-01 01:34:45
  • OfStack

When deploying a webservices program today, from the page to get the data of the servlet, gibberish. I've put the request in the servlet setCharacterEncoding (" GB2312 "); This text is added to the code, but there is still a mess.
  Find information on the Internet, as follows: JAVA is Unicode code, you first converted to iso8859-1, and then converted to GBK or GB2312.

Java code


request.setCharacterEncoding("ISO8859-1");    
ad=request.getParameter("name");    
byte[] temp3 = ad.getBytes("GBK");    
String str = new String(temp3);   

That's Chinese!
An even simpler approach is to set up the encoding transformation directly in the server. I used TOMCAT5.0.28.
In.. \ Tomcat    5.0\conf directory to find the server.xml file, use a clipboard to open it, set as follows:
I can just add an attribute to it, URIEncoding="GBK"
Tests pass, fix, and then request. SetCharacterEncoding (" GB2312 ") this sentence exactly what role, if it can't solve the problem of co-operation, we use it to work, sorting data is as follows:
      (a) the JSP page is in Chinese, but see is after the garbled code:
Solution is the place in the JSP page coding, because of the coding problem of JSP into Java file, the default if some servers are ISO - 8859-1, if direct input the Chinese in a JSP, JSP as iso8859-1 is there must be some problem to deal with, this, we can see Jasper among the generated Java files to confirm

(ii) when the Request object is used to obtain the Chinese code submitted by the customer, garbled codes will appear:
The solution is to configure a filter, which is a Servelet filter, as follows:


public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
request.setCharacterEncoding("GBK");
//Pass control to the next filter
chain.doFilter(request, response);
}

Configure web. XML

<filter></filter>
<filter-name></filter-name>Set Character Encoding
<filter-class></filter-class>SetCharacterEncodingFilter
<filter-mapping></filter-mapping>
<filter-name></filter-name>Set Character Encoding
<url-pattern></url-pattern>/*

If that's still the case with your Form then you can go down and see if you're in the fourth case, if your Form is submitted with get, which is generally fine with post, and if so, you can look at the fourth case.

There is also the information containing Chinese characters for processing, processing code is:

public String toUni(String gbStr){
String uniStr = "";
if(gbStr == null){
gbStr = "";
}
try{
byte[] tempByte = gbStr.getBytes("GB2312");
uniStr = new String(tempByte,"ISO8859_1");
}catch(Exception ex){
}
return uniStr;
}
}

You can also do direct conversion by first encoding the string with iso-8859-1, then storing the code in a byte array, and then converting the array into a string object, such as:
String STR = request. The getParameter (" girl ");
Byte [] B = STR. GetBytes (" ISO - 8859-1 ");
Str = new String (B);
With the above transformation, any information submitted will be displayed correctly.
(iii) when the Formget request USES request-getparameter (" name ") on the server, it returns a gargoyled code; According to the practice of tomcat Settings or Filter to also was not used in the request. SetCharacterEncoding (" GBK "); The problem is in the way the parameters are passed: if the servlet is handled with the doGet(HttpServletRequest request, HttpServletResponse response) method, even if it has written:

request.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");

Also does not work, the return of Chinese or garbled code!! If I change this function to doPost(HttpServletRequest request, HttpServletResponse response), everything will be OK.
Also, when handling form input with two JSP pages, the only way to display Chinese is to use the post method instead of the get method.
This shows that it is important to use the doGet() method in servlets or the get method in JSPS. This, after all, involves passing parameter information through the browser, which can lead to frequent character set conflicts or mismatches.
/ / this place as request. SetCharacterEncoding (" GBK "); The set is the body of the request, rather than the header section, the parameters in the url field when a get request, not in the body, so the time request. SetCharacterEncoding (" GBK "), there is no work, it's no problem to change the post to submit, by the tests pass,!!!!!

The solution is:
1) open the tomcat server.xml file, find the block, and add the following line:
GBK URIEncoding = ""
The complete version should read as follows:


<connector uriencoding="GBK" maxthreads="150" debug="0" redirectport="8443" port="8080" enablelookups="false" maxsparethreads="75" minsparethreads="25" connectiontimeout="20000" disableuploadtimeout="true" acceptcount="100"></connector>

2) restart tomcat, everything is OK.
An explanation from tomact.org
This specifies the character encoding, informs to decode the URI bytes, after % xx decoding the URL. If not specified, ISO - 8859-1 will be 2. That is to say, convert the URI bytes, request the setCharacterEncoding (" GBK ") to request has changed, the problem with respect to ok!

(four) the JSP page has Chinese, the button also has Chinese, but through the server to view the page when the garbled code:
The solution: first, instead of directly containing localized message text in the JSP file, you should go through < Bean: message> The tag gets the text from the Resource Bundle. You should put your Chinese text in the application.properties file, which is under web-inf /classes/*, for example, I have the name and the age in the page, two labels, I will first build an application.properties, the content should be name= "name" age= "age", and then I will put this file under web-inf /classes/properties/, Next, according to the application.properties file, code it and create a Chinese resource file, assuming the name is application_cn.properties. The native2ascii command is provided in the JDK, which enables conversion of character encodings. Find the directory where you put the application. properties file in the DOS environment. Execute the following command in the DOS environment to generate the GBK encoded Chinese resource file application_cn.properties: native2ascii? Encoding GBK application. properties application_cn.properties after executing the above command will generate the following application_cn.properties file: name=u59d3u540d age=u5e74u9f84, configured in struts-config.xml: < The message - resources parameter = "properties. Application_cn" > < / message - resources> . At this point, you're almost halfway there, and then you write on the JSP page, the label to the name is < Bean: message key = "" name" "> , this will appear on the page when the Chinese name, the age is the same, the Chinese characters on the button is the same.
(v) writing to the database is garbled:
Solution: to configure a filter, a Servelet filter, the code is the same as in the second case.
If you are a direct link via JDBC database, the configuration code is as follows: JDBC: mysql: / / localhost: 3306 / workshopdb? UseUnicode =true&characterEncoding=GBK, which ensures that the code in the database is not garble.
If you are using the data source link, you can't write it in this way. First, you should write it in the configuration file. The place to configure the data source in tomcat 5.0.19 is under C: tomcat 5.0confCatalinalocalhost.


<context debug="0" path="/workshop" docbase="workshop"></context>reloadable="true" >
<resource name="jdbc/WorkshopDB"></resource>auth="Container"
type="javax.sql.DataSource" />
<resourceparams name="jdbc/WorkshopDB"></resourceparams>
<parameter></parameter> 
<name></name>factory
<value></value>org.apache.commons.dbcp.BasicDataSourceFactory
<parameter></parameter> 
<name></name>maxActive
<value></value>100
<parameter></parameter> 
<name></name>maxIdle
<value></value>30
<parameter></parameter> 
<name></name>maxWait
<value></value>10000
<parameter></parameter> 
<name></name>username
<value></value>root
<parameter></parameter> 
<name></name>password
<value></value>
<parameter></parameter> 
<name></name>driverClassName
<value></value>com.mysql.jdbc.Driver
<parameter></parameter> 
<name></name>url
<value></value>

The bold text should be particularly noted, and there is a difference between direct JDBC links, if you are configured correctly, when you enter Chinese into the database is Chinese, one thing to note is that you also need to use this line of code in the display of data page. It's important to note that some of the reception staff after the code is written in Dreamver, wrote a Form when he changed to a JSP, so there is a place to note, that is the Action in the Dreamver submission is a request, you need to put he should come here, because in the process of JSP submission is tightly POST and GET one of two ways, but the two ways to submit code or have very big different, in terms of coding the place behind. < / bean: message> < / bean: message>


Related articles: