jsp+ MySQL Chinese garbled problem post submit garbled solution _jsp programming

Source: Internet
Author: User
Tags stmt server port
Wrote two JSP pages index.jsp and mysql_insert.jsp. The process of data processing is: After accessing index.jsp on the browser (chrome), enter data on its form, submit to mysql_insert.jsp,mysql_insert.jsp to first send the received data by variable to MySQL Html_ DB Database Person_tb (the original part of the table), and then mysql_insert.jsp the table with all the data displayed on the mysql_insert.jsp page.

It is now found that when the submitted data contains Chinese (for example, the value of the variable name is Chinese), the Mysql_ Insert.jsp page shows the new record in the corresponding Chinese (name value) garbled, the other data are displayed normal, view the database, found that the corresponding contains Chinese variables (name value) garbled. Garbled situation as shown below:

Index.jsp the first line has a statement: <%@ page contenttype= "text/html;charset=gb2312"%>, in the browser (Chrome) Access to this page is not garbled (mainly refers to Chinese garbled, The English garbled phenomenon has not met yet. (Try to change gb2312 into Utf-8, after the visit Chinese garbled)
The first line in the mysql_insert.jsp has a statement: <% @page language= "java" pageencoding= "UTF-8"%&gt, and there are no garbled characters when accessing this page directly in the browser.
The code for the Mysql_insert.jsp page is as follows:
Copy Code code as follows:

<% @page language= "java" pageencoding= "UTF-8"%>
<%@ page import= "java.sql.*"%>
<HTML>
<HEAD>
<title>add Message into table </TITLE>
</HEAD>
<BODY>
<%
String id=request.getparameter ("id"); Get from Form
String name=request.getparameter ("name"); Get from Form
String sex=request.getparameter ("sex"); Get from Form
String age=request.getparameter ("Age"); Get from Form
Try
{
/** Connection Database Parameters **/
String drivername = "Com.mysql.jdbc.Driver"; Driver name
String dbuser = "root"; MySQL User name
String dbpasswd = "123456"; MySQL Password
String dbname = "html_db"; Database name

String Connurl = "jdbc:mysql://localhost/" + dbname + "? user=" + Dbuser + "&password=" + dbpasswd;
Class.forName (drivername). newinstance ();
Connection conn = drivermanager.getconnection (Connurl);
Statement stmt = Conn.createstatement ();
Stmt.executequery ("SET NAMES UTF8");
String insert_sql = "INSERT into PERSON_TB values (' + ID +" ', ' "+ name +" ', ' + Sex + "', ' +" + "+") ";
String query_sql = "SELECT * from PERSON_TB";

try {
Stmt.execute (Insert_sql);
}catch (Exception e) {
E.printstacktrace ();
}
try {
ResultSet rs = stmt.executequery (query_sql);
while (Rs.next ()) {
%>
Id:<%=rs.getstring ("id")%> </br>
Name: <%=rs.getstring ("name")%> </br>
Sex: <%=rs.getstring ("Sex")%> </br>
Ages: <%=rs.getstring ("Age")%> </br> </br>
<%
}
}catch (Exception e) {
E.printstacktrace ();
}
Rs.close ();
Stmt.close ();
Conn.close ();
}catch (Exception e) {
E.printstacktrace ();
}
%>
</body>

My database is set to use all UTF-8 encoding, as shown in the following figure:

The web.xml contents of my virtual directory are as follows:

The contents of the Server.xml file under the tomcat/conf directory are as follows:
Copy Code code as follows:

<u><?xml version= ' 1.0 ' encoding= ' utf-8 '?></u>
<server port= "8005" shutdown= "Shutdown" >
<listener classname= "Org.apache.catalina.core.AprLifecycleListener" sslengine= "on"/>
<listener classname= "Org.apache.catalina.core.JasperListener"/>
<listener classname= "Org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<listener classname= "Org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<listener classname= "Org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<GlobalNamingResources>
<resource name= "Userdatabase" auth= "Container"
Type= "Org.apache.catalina.UserDatabase"
description= "User database" can be updated and saved "
factory= "Org.apache.catalina.users.MemoryUserDatabaseFactory"
Pathname= "Conf/tomcat-users.xml"/>
</GlobalNamingResources>
<service name= "Catalina" >
<connector port= "8080" protocol= "http/1.1"
connectiontimeout= "20000"
redirectport= "8443"/>
<connector port= "8009" protocol= "ajp/1.3" redirectport= "8443"/>

<engine name= "Catalina" defaulthost= "localhost" >
<realm classname= "Org.apache.catalina.realm.LockOutRealm" >
<realm classname= "Org.apache.catalina.realm.UserDatabaseRealm"
Resourcename= "Userdatabase"/>
</Realm>
<valve classname= "Org.apache.catalina.valves.AccessLogValve" directory= "Logs"
Prefix= "Localhost_access_log." suffix= ". txt"
pattern= "%h%l%u%t"%r "%s%b"/>
</Host>
</Engine>
</Service>
</Server>

The main contents of the Web.xml file under the tomcat/conf directory are as follows:
Copy Code code as follows:

<u><?xml version= "1.0" encoding= "UTF-8"?></u>
<web-app xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "
version= "3.0" >
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--the mappings for the JSP servlet-->
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspx</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
< omitted the contents of the Mime-mapping >
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Now I can think of the setting coding of the place is only so much, and other where to set the code? begged for guidance.
hahaha, after my hard exploration, finally found the reason for garbled, of course, garbled problem has been solved. My brother recommended that all codes be used UTF-8, so I also recommend that readers do the same, and that the benefits are great.
Below I introduce my resolution process:
The first step: after I found that there are garbled, my first thought is whether I set a place in the coding error caused, and MySQL set is correct (My.ini set), is all set to UTF8. So I don't need to modify the settings under MySQL.
Step two: Then Tomcat, this thing to the data I submitted to deal with, there are many people on the internet need to set the Web.xml and Server.xml inside the code, which is mainly in Server.xml add uriencoding= "UTF-8", The specific setting is: <connector port= "8080" protocol= "http/1.1" connectiontimeout= "20000" redirectport= "8443" "URIEncoding=" UTF-8 "/>. After I finished this step of the setup test again, found still garbled. Keep This step of the changes and proceed to the next steps.
Step three: Back to the. JSP page, I tried to set all the coding and character sets to UTF-8 (the first line I wrote in index.jsp was <% @page language= "java contenttype=" text/html; charset=gb2312 "%>, now use Dreamweaver to open index.jsp modify it to Charset=utf-8), Then in the browser direct access to index.jsp found in Chinese garbled, so close the Dreamweaver, use myeclipse reopen index.jsp file, found in the code in Chinese is garbled, decisively modified into the correct characters, while retaining just the changes to the charset, that is still using CH Arset=utf-8, and then again in the browser to access the index.jsp, and finally the Chinese characters are normal display. (After this farewell Dreamweaver, I spared a lot of road) then I entered the Chinese data on the INDEX.JSP page and submitted, is still Chinese garbled. After making this step change, my two. jsp file has the following two sentences on the head:
<%@ page language= "java" pageencoding= "Utf-8"%>
<%@ page contenttype= "Text/html;charset=utf-8"%>

The fourth step: I just think, in the end is to data inventory data caused by garbled or data from the database when the resulting garbled it? Or is the transfer of data to the mysql_insert.jsp after the submission of the page caused by garbled? Then I insert a data directly into the database that contains Chinese characters, and then access mysql_insert.jsp directly in the browser, and find that Chinese characters are displayed correctly. That is to say, is in the data, or transmission data garbled. Then how to set to not pass data, stored data not garbled?
The fifth step: Find the following on the Internet, find this content, very useful:
1, the JSP page coding method has two places to set up:
Copy Code code as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>
<%@ page contenttype= "Text/html;charset=utf-8"%>

Wherein: Pageencoding refers to the encoding of the JSP file itself when it is saved locally. The charset of ContentType is the encoding used by the server when it sends the content of the Web page to the client.
From the first visit to a JSP page, to the page to be sent to the client, the JSP page to go through the three-time code conversion:
The first stage is JSP compiled into. Java, which reads the JSP according to the pageencoding settings, resulting in the translation of the specified coding scheme into a unified UTF-8 Java source code (that is, Java), if the pageencoding set wrong, or did not set, out is the Chinese garbled.
The second phase is from Javac Java source to the Java bytecode compiled, regardless of the JSP when the encoding scheme used, after this phase of the results are all UTF-8 encoding Java source code.
Javac uses UTF-8 's encoding to read Java source code, compiled into UTF-8 encoding binary code (that is,. Class), which is the JVM's specification for regular numeric strings expressed in binary (Java encoding).
The third stage is the Java binary Code of Tomcat (or its application container) loading and executing phase two, and the output result, which is seen at the client, is hidden in the parameters of stage one and phase two, and contenttype is effective.
So the Final solution is:
One of the pageencoding or contenttype in the JSP page is an encoding format (such as utf-8,gbk,gb2312) that supports Chinese. Because one is set, another default will be the same as it.
If all two are set, you must ensure that all two support Chinese encoding (not necessarily the same).
The best recommended settings are as follows:
<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%>
<%@ page contenttype= "Text/html;charset=utf-8"%>

2, Post way to pass the value garbled:
Because the post method is stored through the request and the information is extracted by Request.getparameter (String name) on another page, the garbled code is mainly caused by the encoding setting of the request store information. When the post is submitted, if the submitted encoding format is not set, it is submitted in a iso8859-1 manner and the accepted JSP is accepted in a utf-8 manner. So use the following statement to get a single correct Chinese string: string str = new String (Request.getparameter ("something"). GetBytes ("Iso-8859-1"), "Utf-8");
Workaround:
Set request.setcharacterencoding ("UTF-8") on the receiving page.
Second, the best through the filter to achieve each page is set to Request.setcharacterencoding ("UTF-8").
Use a statement on the page that sends the data to specify that the data be sent using the UTF-8 format.
3, get way to pass the value garbled:
There are two types of get-pass values, one is a form get-pass value, the other is a URL-address-passing value (essentially, both of which are passed in the form of a URL parameter).
Form method Get Pass value:
Form method get pass the encoding process of the value, first the browser according to the page charset encoding way to encode the value, and then submit to the server to Tomcat,tomcat to decode this information, The decoding method used is determined by the uriencoding setting in the Server.xml file, that is, when we use the command Request.getparameter ("") to get the form parameter values, the resulting string, After the charset encoding and decoding of the uriencoding.

As far as we know, as long as the charset encoding and uriencoding decoding consistent, and support Chinese, can guarantee no garbled.
The following methods are set up for uriencoding:
Method One:
Modify the $tomcat/conf/server.xml file to add uriencoding= "UTF-8" to the HTTP connector or AJP connector configuration
Copy Code code as follows:

The maxthreads= "minsparethreads=" maxsparethreads= "75"
Enablelookups= "false" redirectport= "8443" acceptcount= "100"
connectiontimeout= "20000" disableuploadtimeout= "true" uriencoding= "UTF-8"/>

Method Two:
Use usebodyencodingforuri= "true". This method is suitable for your Tomcat instance when you need to run multiple different encoding programs.
Copy Code code as follows:

The maxthreads= "minsparethreads=" maxsparethreads= "75"
Enablelookups= "false" redirectport= "8443" acceptcount= "100"
connectiontimeout= "20000" disableuploadtimeout= "true" usebodyencodingforuri= "true"/>
Enablelookups= "false" redirectport= "8443" protocol= "ajp/1.3" usebodyencodingforuri= "true"/>

In the Tomcat configuration, the connector (HTTP Connector) attribute has a uriencoding and
The Usebodyencodingforuri property, which sets how to select the character set encoding when URL decoding of additional parameters after the URL is performed. Uriencoding the character set encoding for additional parameters after the URL is used, Usebodyencodingforuri indicates whether to use the character set encoding settings of the entity content instead of the uriencoding settings, that is, when When the Usebodyencodingforuri property is set to True, the character set encoding that is set by the Servletrequest.setcharacterencoding method also affects the result of URL decoding of the parameters of the URL address by methods such as GetParameter. (Find <Connector> mark in/%tomcat_home%/conf\server.xml file, then add Usebodyencodingforuri=true to the back)
URL way Get pass value garbled:
In this way, the browser does not use the charset of the page to encode the Chinese in the URL and submit it to the server (Ie,firefox is the same), but instead use the system's GBK transcoding to iso-8859-1 and then submit to server Tomcat, so this process is:
First of all, the Chinese in the URL address is converted from GBK to Iso-8859-1, after being handed to Tomcat, then Tomcat is decoded according to Urlecoding, Only the urlecoding set to GBK in order to Request.getparameter ("") does not appear garbled. But this will affect the configuration above, so a good solution is to use Java.net.URLEcoder and Urldecoder to manually encode and decode the Chinese in the address.
So a foolproof solution is:
1 The charset of all pages is set to UTF-8.
2 Tomcat uriencoding default is Iso-8859-1, and I set to UTF-8, mainly want to solve the Chinese named file and request to get way to submit a possible garbled problem.
3) Add filter, call Request.setcharacterencoding ("Utf-8") method to set the character set of request to Utf-8, to resolve requests to post the garbled problem.
4 when the Chinese parameter exists in the URL address, the Chinese parameter is first encoded with the Urlecoder Utf-8, then the Request.getparameter ("") receives the parameter and then uses the Urldecoder restore. For example:
from.jsp page:
Copy Code code as follows:

<%string username = "Zhang So-and-so";
Username = Urlencoder.encode (username, "utf-8");
%>
<a href= "To.jsp?param=<%=username%>" > Transfer </a>

to.jsp page
Copy Code code as follows:

<%=urldecoder.decode (Request.getparameter ("param"), "Utf-8")%>

In short, the garbled solution is as follows:
When post pass value is garbled, set request.setcharacterencoding ("UTF-8") at the receiving end
Get pass value or URL garbled, manually set the received parameter String str = new String (Request.getparameter ("something"). GetBytes ("Iso-8859-1"), "Utf-8");
The get,post values are not the same in TOMCAT5 as they are visible from above.
After reading the contents of the red Word, I decided to submit the data in the UTF-8 format to submit the data, and at the same time receive the data in the page settings to UTF-8 receive data, so I have two pages in the header added the following statement:
<%
Request.setcharacterencoding ("UTF-8");
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("text/html; Charset=utf-8 ");
%>

Then test, OK! There's no garbled!
Now, the code for the Index.jsp page is as follows:
Copy Code code as follows:

<%@ page language= "java" pageencoding= "Utf-8"%>
<%@ page Conte Nttype= "Text/html;charset=utf-8"%>
<%
request.setcharacterencoding ("UTF-8");
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("text/html; Charset=utf-8 ");
%>
<body>
<form action= Mysql_insert . JSP method= "POST" >
ID: <input type = "Text" name= "id" value= "0"/>
Name: <input type = "Text" Name= "Name" value= "aaa"/>
Sex: <input type = "text" name= "Sex" value= "female"/>
Age: <input type = "Text" Name= ' age ' value= '/>
</br>
<input type = ' Submit ' value= ' Submit '/>
</form>
;/body>
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.