Garbled code solution for passing values between Java and JSP

Source: Internet
Author: User

The default encoding method in Java is Unicode, so it is easy to use Chinese characters. The common solution is

Java code
1. String S2 = new string (s1.getbytes ("ISO-8859-1"), "UTF-8 ");
String S2 = new string (s1.getbytes ("ISO-8859-1"), "UTF-8"); 1, utf8 to solve the JSP Chinese garbled problem:
Generally, at the beginning of each page, add:

JSP code
1. <% @ page Language = "Java" contenttype = "text/html; charset = UTF-8"
2. pageencoding = "UTF-8" %>
3. <% request. setcharacterencoding ("UTF-8"); %>
<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8"
Pageencoding = "UTF-8" %>
<% Request. setcharacterencoding ("UTF-8"); %> charset = UTF-8 is used to specify the encoding method that JSP outputs to the client as "UTF-8 ".
Pageencoding = "UTF-8" is effective in Linux to allow the JSP Engine to correctly decode JSP pages containing Chinese characters.
Request. setcharacterencoding ("UTF-8"); is a Chinese encoding of the request.
 
Sometimes, this still cannot solve the problem. You need to handle it as follows:

Java code
1. String MSG = request. getparameter ("message ");
2. String STR = new string (msg. getbytes ("ISO-8859-1"), "UTF-8 ");
3. Out. println (STR );
String MSG = request. getparameter ("message ");
String STR = new string (msg. getbytes ("ISO-8859-1"), "UTF-8 ");
Out. println (STR );

2. Tomcat 5.5 Chinese garbled characters:
 
(1). As long as % tomcat installation directory %/webapps/Servlets-examples/WEB-INF/classes/filters/setcharacterencodingfilter. Class File

Copy it to your webapp directory/filters. If there is no filters directory, create one.
(2) Add the following lines to your web. xml:

XML Code
1. <filter>
2. <filter-Name> set character encoding </filter-Name>
3. <filter-class> filters. setcharacterencodingfilter </filter-class>
4. <init-param>
5. <param-Name> encoding </param-Name>
6. <param-value> GBK </param-value>
7. </init-param>
8. </filter>
9. <filter-mapping>
10. <filter-Name> set character encoding </filter-Name>
11. <URL-pattern>/* </url-pattern>
12. </filter-mapping>
<Filter>
<Filter-Name> set character encoding </filter-Name>
<Filter-class> filters. setcharacterencodingfilter </filter-class>
<Init-param>
<Param-Name> encoding </param-Name>
<Param-value> GBK </param-value>
</Init-param>
</Filter>
<Filter-mapping>
<Filter-Name> set character encoding </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping> (3). Complete.
Solution to get:
(1) Open the Tomcat server. xml file, find the block, add the following line: uriencoding = "UTF-8"
The complete information should be as follows:

Java code
1. <Connector
2. Port = "80" maxthreads = "150" minsparethreads = "25" maxsparethreads = "75"

3. enablelookups = "false" redirectport = "8443" acceptcount = "100"
4. DEBUG = "0" connectiontimeout = "20000"
5. disableuploadtimeout = "true"
6. uriencoding = "UTF-8"/>
<Connector
Port = "80" maxthreads = "150" minsparethreads = "25" maxsparethreads = "75"
Enablelookups = "false" redirectport = "8443" acceptcount = "100"
DEBUG = "0" connectiontimeout = "20000"
Disableuploadtimeout = "true"
Uriencoding = "UTF-8"/>

(2) Restart tomcat. Everything is OK.

3. XMLHttpRequest Chinese

JSP page with the UTF-8 Encoding:
Code

JSP code
1. <% @ page contenttype = "text/html; charset = GBK" %>
<% @ Page contenttype = "text/html; charset = GBK" %>

Javascript section:

JS Code
1. Function addfracasreport (){
2. var url = "Servlet/encodingservlet ";
3. // var urlmsg = "& reportid =" + fracasreport1.textreportid. value; // fault report table No.
4. var XMLHTTP = createxmlhttprequest ();
5. XMLHTTP. onreadystatechange = function (){
6. // The object state is 4, indicating that it has been completed
7. If (XMLHTTP. readystate = 4 ){
8. // 200 is returned successfully. If no modification is made, 304 is returned.
9. If (XMLHTTP. Status = 200 | XMLHTTP. Status = 304 ){
10. // start processing information
11. // alert (xhr. responsetext );
12. Alert ("request sent successfully ");
13 .}
14 .}
15 .}
16. XMLHTTP. Open ("Post", URL, true );
17. XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");

18. var urlmsg = "Hello = Hello & World = World"
19. XMLHTTP. Send (urlmsg );
20 .}
Function addfracasreport (){
VaR url = "Servlet/encodingservlet ";
// Var urlmsg = "& reportid =" + fracasreport1.textreportid. value; // fault report table No.
VaR XMLHTTP = createxmlhttprequest ();
XMLHTTP. onreadystatechange = function (){
// The object state is 4, indicating that it has been completed
If (XMLHTTP. readystate = 4 ){
// 200 is returned for success. If no modification is made, 304 is returned.
If (XMLHTTP. Status = 200 | XMLHTTP. Status = 304 ){
// Start processing information
// Alert (xhr. responsetext );
Alert ("request sent successfully ");
}
}
}
XMLHTTP. Open ("Post", URL, true );
XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
VaR urlmsg = "Hello = Hello & World = World"
XMLHTTP. Send (urlmsg );
} At this time, if the front-end reference JS Code JSP pages are all UTF-8 encoding, then after the acquisition, there will be no garbled problem, for example, in servlet with string

Hello = request. getparameter ("hello"); get and use system. Out. println (Hello); output to the console.

Response. getwriter (). Print (Hello); if it is output to the page, garbled characters may occur, which can be used in Servlet

Response. setcharacterencoding ("UTF-8"); transcode.

4. Toad Character Set setting and Oracle Installation
Oracle Database Server installation is generally a Chinese character set, sometimes installed on different platforms, set to ISO encoding, toad is the best tool for Oracle development, not

I said, but when toad is installed in a Chinese environment and Oracle with English characters is opened, all Chinese characters are garbled. Must be set.

Environment variables-> System Variables
Add nls_lang = simplified chinese_china.zhs16gbk

Or

Nls_lang = american_america.we8iso8859p1 american_america.we8mswin1252

Or

Open the registry, click hkey_local_mathine, click software, and then oracle. Click home (the Oracle directory ).

Nls_lang, double-click it to overwrite the original one you want. It is best to write down the old one so that it can be changed back.

SQL code
1. Connect sys/change_on_install
2. Update props $
3. Set Value $ = 'zhs16cgb231280'
4. Where name = 'nls _ characterset ';
5. commit;
Connect sys/change_on_install
Update props $
Set Value $ = 'zhs16cgb231280'
Where name = 'nls _ characterset ';
Commit; then OK

5. How to Solve GWT (Google Web Toolkit) Chinese problems
GWT Chinese garbled Solution

(1) input the Chinese "test string" you want to display to a file, for example, 1.txt
(22.16.enter the command line, enter the directory where 1.txt is located, and enter the following command: native2ascii.exe 1.txt 2.txt and press Enter. In this case, another file 2.txt is generated.

.
(32.16.2.txt content: \ u6d4b \ u8bd5 \ u5b57 \ u7b26 \ u4e32
(4). Use the above encoding and use it in GWT.

6. How is the webpage obtained by XMLHTTP garbled?
(1). Use webrequest on the server side instead of XMLHTTP.
(2). Set streamreader sr = new streamreader (Stream );
For Simplified Chinese, change:
Streamreader sr = new streamreader (stream, encoding. Default );
For UTF-8:
Streamreader sr = new streamreader (stream, encoding. utf8 );
Of course, there are many other Members in the encoding enumeration, which can be used for different encoding content-types.
(3) later I found that whether the Content-Type is gb2312 or UTF-8
Streamreader sr = new streamreader (stream, encoding. Default );
Can return normal Chinese characters, so unified change to encoding. Default
Finally, the Code for obtaining the source code of a webpage from a URL on the server is as follows:

Java code
1. /// <summary>
2. // post a specified URL to obtain the source code of the webpage (implemented using webrequest)
3. /// </Summary>
4. /// <Param name = "url"> </param>
5. /// <returns>
6. // if the request fails, null is returned.
7. // if the request is successful, the source code of the webpage is returned.
8. /// </returns>
9. Public static string getcontentfromurl2 (string URL)
10 .{
11. // variable definition
12. String respstr;
13.
14. webrequest mywebrequest = webrequest. Create (URL );
15. // mywebrequest. preauthenticate = true;
16. // networkcredential = new networkcredential (username, password, domain );

17. // mywebrequest. Credentials = networkcredential;
18.
19. // assign the response object of 'webrequest' to a 'webresponse' variable.

20. webresponse mywebresponse = mywebrequest. getresponse ();
21. system. Io. Stream stream = mywebresponse. getresponsestream ();
22. streamreader sr = new streamreader (stream, encoding. Default );
23. // read the data stream as a string
24. respstr = Sr. readtoend ();
25. sr. Close ();
26.
27. Return respstr;
28.
29 .}
/// <Summary>
/// Post a specified URL to obtain the source code of the webpage (implemented using webrequest)
/// </Summary>
/// <Param name = "url"> </param>
/// <Returns>
/// If the request fails, null is returned.
/// If the request is successful, the source code of the webpage is returned
/// </Returns>
Public static string getcontentfromurl2 (string URL)
{
// Variable definition
String respstr;

Webrequest mywebrequest = webrequest. Create (URL );
// Mywebrequest. preauthenticate = true;
// Networkcredential = new networkcredential (username, password, domain );
// Mywebrequest. Credentials = networkcredential;

// Assign the response object of 'webrequest' to a 'webresponse' variable.
Webresponse mywebresponse = mywebrequest. getresponse ();
System. Io. Stream stream = mywebresponse. getresponsestream ();
Streamreader sr = new streamreader (stream, encoding. Default );
// Read data streams as strings
Respstr = Sr. readtoend ();
Sr. Close ();

Return respstr;

}

7. Solve the WebLogic/webshpere Chinese problem:
Configure the Chinese environment in the web. xml file. As follows:

XML Code
1. <context-param>
2. <param-Name> weblogic. httpd. inputcharset./* </param-Name>
3. <param-value> gb2312 </param-value>
4. </context-param>
<Context-param>
<Param-Name> weblogic. httpd. inputcharset./* </param-Name>
<Param-value> gb2312 </param-value>
</Context-param>

8. Use JS transition to transcode and receive messages in Java classes (applicable to WebSphere ).

JS Code
1. // the front-end JS Code is as follows:
2. var url = straction + "? Method = startproc & proname = "+ encodeuri ('Chinese character to be uploaded '));

// The front-end JS Code is as follows:
VaR url = straction + "? Method = startproc & proname = "+ encodeuri ('Chinese character to be uploaded '));

Java code
1. // decode the following in the background action:
2. zjmc = java.net. urldecoder. Decode ('character to be passed ', "UTF-8 ");
3. system. Out. println (zjmc );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.