一般在傳送時(shí)使用的encoding:
使用GET 的方式:
String test = new String((request.getParameter("test")).getBytes("ISO-8859-1"),"GBK");
使用POST 的方式:
request.setCharacterEncoding("GBK");
pageEncoding及contentType的作用:<%@ page pageEncoding="GBK" %>
pageEncoding是當(dāng)jsp轉(zhuǎn)譯成_jsp.java時(shí)使用的encoding.預(yù)設(shè)是iso8859_1.
然後_jsp.java編譯成_jsp.class是使用utf-8作為encoding.
response.setContentType("text/html; charset=GBK");
or
<%@ page contentType="text/html;charset=GBK" %>
就是輸出到瀏覽器時(shí)的編碼,預(yù)設(shè)是iso8859_1.
這樣瀏覽器才知道應(yīng)該用甚麼charset來顯示.
資料庫輸出到j(luò)sp出現(xiàn)亂碼:第一,檢查一下你database里的資料是否亂碼.
如果database里的資料是亂碼,檢查一下再進(jìn)入資料庫時(shí)request接收後資料是否是亂碼.
即忘了加入request.setCharacterEncoding(String charset);
request.setCharacterEncoding(String charset)把表單傳送過來的資料以charset的字型來encoding.
如果接收時(shí)是正常的.但資料庫是亂碼,
那就檢查一下database的編碼設(shè)定.
如果資料庫的資料正常.但輸出到j(luò)sp的資料是亂碼.
以mysql為例:
String connect = "jdbc:mysql://localhost/dbname?user=&password=&useUnicode=true&characterEncoding=GBK";
就上面的mysql的例子.
需要設(shè)定useUnicode為true.
而characterEncoding=GBK必須與contentType的charset一樣.
mysql的設(shè)定檔my.ini:
[client] default-character-set=GBK
[mysqld] default-character-set=GBK
以下連結(jié)則介紹了access的jdbc:odbc的編碼:http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/bridge.html
include資料出現(xiàn)亂碼:舊的版本tomcat是不能在每一頁jsp中加入
<%@ page contentType="text/html; charset=GBK" %>
tomcat 5.x之後是可以每一頁都加入上面那一句的.
會(huì)必須include的page及被include的page的編碼要相同.連大小寫都要相同.
但這樣做不是最好的方法.
其實(shí)可以在你的web application底下的web.xml的<web-app>里加入:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
?? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
?? xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
?? http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"version="2.4">
.........
.........??
<jsp-config>
<jsp-property-group>??
??<description>jsp encoding example</description>
??<display-name>JSPConfiguration</display-name>
??<url-pattern>*.jsp</url-pattern>
??<el-ignored>true</el-ignored>
??<page-encoding>GBK</page-encoding>
??<scripting-invalid>false</scripting-invalid>
??<include-prelude></include-prelude>
??<include-coda></include-coda>
??<description>html encoding example</description>
??<display-name>JSPConfiguration</display-name>??
??<url-pattern>*.html</url-pattern>??
??<el-ignored>true</el-ignored>
??<page-encoding>GBK</page-encoding>
??<scripting-invalid>false</scripting-invalid>
??<include-prelude></include-prelude>??
??<include-coda></include-coda>
</jsp-property-group>
</jsp-config>
.........
.........
</web-app>
apache整合tomcat 中文問題:apache+tomcat+JK2集成時(shí),http的請求是通過jk2的ajp13轉(zhuǎn)到tomcat的8009端口處理的,
所以要修改tomcat/conf/server.xml中的以下兩項(xiàng)
1 <Connector port="8080" …… URIEncoding="GBK" >
2 <Connector port="8009" …… URIEncoding="GBK" >
都加上URIEncoding="GBK"。