這些天開發一個項目,服務器是tomcat,操作系統是xp,採用的是MVC架構,模式是採用Facade模式,總是出現亂碼,自己也解決了好多天,同事 也幫忙解決,也參考了網上衆多網友的文章和意見,總算是搞定。但是好記性不如爛筆桿,所以特意記下,以防止自己遺忘,同時也給那些遇到同樣問題的人提供一 個好的參考途徑:
(一) JSP頁面上是中文,但是看的時候是亂碼:
解 決的辦法就是在JSP頁面的編碼的地方<% @ page language="java" contentType="text/html;charset=GBK" %>,因爲Jsp轉成 Java文件時的編碼問題,默認的話有的服務器是ISO-8859-1,如果一個JSP中直接輸入了中文,Jsp把它當作ISO8859-1來處理是肯定 有問題的,這一點,我們可以通過查看Jasper所生成的Java中間文件來確認
(二) 當用Request對象獲取客戶提交的漢字代碼的時候,會出現亂碼:
解決的辦法是:要配置一個filter,也就是一個Servelet的過濾器,代碼如下:
001 002 package com.xxx.utils; 003 004 import org.apache.commons.logging.Log; 005 import org.apache.commons.logging.LogFactory; 006 007 import java.io.IOException; 008 import javax.servlet.Filter; 009 import javax.servlet.FilterChain; 010 import javax.servlet.FilterConfig; 011 import javax.servlet.ServletException; 012 import javax.servlet.ServletRequest; 013 import javax.servlet.ServletResponse; 014 015 016 /** 017 * <p>Filter that sets the character encoding to be used in parsing the 018 * incoming request.</p> 019 * <p>Configuration of this filter is based on 020 * the following initialization parameters:</p> 021 * <ul> 022 * <li><strong>encoding</strong> - The character encoding to be configured 023 * for this request, either conditionally or unconditionally based on 024 * the <code>ignore</code> initialization parameter. This parameter 025 * is required, so there is no default.</li> 026 * <li><strong>ignore</strong> - If set to "true", any character encoding 027 * specified by the client is ignored, and the value returned by the 028 * <code>selectEncoding()</code> method is set. If set to "false, 029 * <code>selectEncoding()</code> is called <strong>only</strong> if the 030 * client has not already specified an encoding. By default, this 031 * parameter is set to "true".</li> 032 * </ul> 033 * <p/> 034 * <p>Although this filter can be used unchanged, it is also easy to 035 * subclass it and make the <code>selectEncoding()</code> method more 036 * intelligent about what encoding to choose, based on characteristics of 037 * the incoming request (such as the values of the <code>Accept-Language</code> 038 * and <code>User-Agent</code> headers, or a value stashed in the current 039 * user's session.</p> 040 * 041 */ 042 043 public class SetCharacterEncodingFilter implements Filter { 044 /** 045 * Logger for this class 046 */ 047 private static final Log logger = LogFactory 048 .getLog(SetCharacterEncodingFilter.class); 049 050 051 // ----------------------------------------------------- Instance Variables 052 053 054 /** 055 * The default character encoding to set for requests that pass through 056 * this filter. 057 */ 058 protected String encoding = null; 059 060 061 /** 062 * The filter configuration object we are associated with. If this value 063 * is null, this filter instance is not currently configured. 064 */ 065 protected FilterConfig filterConfig = null; 066 067 068 /** 069 * Should a character encoding specified by the client be ignored? 070 */ 071 protected boolean ignore = true; 072 073 074 // --------------------------------------------------------- Public Methods 075 076 077 /** 078 * Take this filter out of service. 079 */ 080 public void destroy() { 081 this.encoding = null; 082 this.filterConfig = null; 083 } 084 085 086 /** 087 * Select and set (if specified) the character encoding to be used to 088 * interpret request parameters for this request. 089 * 090 * @param request The servlet request we are processing 091 * @param response The servlet response we are creating 092 * @param chain The filter chain we are processing 093 * @throws IOException if an input/output error occurs 094 * @throws ServletException if a servlet error occurs 095 */ 096 public void doFilter(ServletRequest request, ServletResponse response, 097 FilterChain chain) 098 throws IOException, ServletException { 099 try { 100 // Conditionally select and set the character encoding to be used 101 if (ignore || (request.getCharacterEncoding() == null)) { 102 String encoding = selectEncoding(request); 103 if (encoding != null) 104 request.setCharacterEncoding(encoding); 105 } 106 107 // Pass control on to the next filter 108 chain.doFilter(request, response); 109 } catch (IOException e) { 110 logger.warn(e.getMessage(), e); 111 throw e; 112 } catch (ServletException e) { 113 logger.warn(e.getMessage(), e); 114 throw e; 115 } 116 } 117 118 119 /** 120 * Place this filter into service. 121 * 122 * @param filterConfig The filter configuration object 123 */ 124 public void init(FilterConfig filterConfig) throws ServletException { 125 this.filterConfig = filterConfig; 126 this.encoding = filterConfig.getInitParameter("encoding"); 127 String value = filterConfig.getInitParameter("ignore"); 128 if (value == null) 129 this.ignore = true; 130 else if (value.equalsIgnoreCase("true")) 131 this.ignore = true; 132 else if (value.equalsIgnoreCase("yes")) 133 this.ignore = true; 134 else 135 this.ignore = false; 136 } 137 138 139 // ------------------------------------------------------ Protected Methods 140 141 142 /** 143 * Select an appropriate character encoding to be used, based on the 144 * characteristics of the current request and/or filter initialization 145 * parameters. If no character encoding should be set, return 146 * <code>null</code>. 147 * <p/> 148 * The default implementation unconditionally returns the value configured 149 * by the <strong>encoding</strong> initialization parameter for this 150 * filter. 151 * 152 * @param request The servlet request we are processing 153 */ 154 protected String selectEncoding(ServletRequest request) { 155 return (this.encoding); 156 } 157 158 } |
Java2html |
配置web.xml
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>
com.ipedo.utils.SetCharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
如果你的還是出現這種情況的話你就往下看看是不是你出現了第四中情況,你的Form提交的數據是不是用get提交的,一般來說用post提交的話是沒有問題的,如果是的話,你就看看第四中解決的辦法。
還有就是對含有漢字字符的信息進行處理,處理的代碼是:
01 package dbJavaBean; 02 03 public class CodingConvert 04 { 05 public CodingConvert() 06 { 07 // 08 } 09 public String toGb(String uniStr){ 10 String gbStr = ""; 11 if(uniStr == null){ 12 uniStr = ""; 13 } 14 try{ 15 byte[] tempByte = uniStr.getBytes("ISO8859_1"); 16 gbStr = new String(tempByte,"GB2312"); 17 } 18 catch(Exception ex){ 19 } 20 return gbStr; 21 } 22 23 public String toUni(String gbStr){ 24 String uniStr = ""; 25 if(gbStr == null){ 26 gbStr = ""; 27 } 28 try{ 29 byte[] tempByte = gbStr.getBytes("GB2312"); 30 uniStr = new String(tempByte,"ISO8859_1"); 31 }catch(Exception ex){ 32 } 33 return uniStr; 34 } 35 } |
Java2html |
你也可以在直接的轉換,首先你將獲取的字符串用ISO-8859-1進行編碼,然後將這個編碼存放到一個字節數組中,然後將這個數組轉化成字符串對象就可以了,例如:
String str=request.getParameter(“girl”);
Byte B[]=str.getBytes(“ISO-8859-1”);
Str=new String(B);
通過上述轉換的話,提交的任何信息都能正確的顯示。
(三) 在Formget請求在服務端用request. getParameter(“name”)時返回的是亂碼;按tomcat的做法設置Filter也沒有用或者用 request.setCharacterEncoding("GBK");也不管用問題是出在處理參數傳遞的方法上:如果在servlet 中用doGet(HttpServletRequest request, HttpServletResponse response)方法進行處理的話前面即使是寫了:
request.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
也是不起作用的,返回的中文還是亂碼!!!如果把這個函數改成doPost(HttpServletRequest request, HttpServletResponse response)一切就OK了。
同樣,在用兩個JSP頁面處理表單輸入之所以能顯示中文是因爲用的是post方法傳遞的,改成get方法依舊不行。
由此可見在servlet中用doGet()方法或是在JSP中用get方法進行處理要注意。這畢竟涉及到要通過瀏覽器傳遞參數信息,很有可能引起常用字符集的衝突或是不匹配。
解決的辦法是:
1) 打開tomcat的server.xml文件,找到區塊,加入如下一行:
URIEncoding=”GBK”
完整的應如下:
<Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="GBK"/>
2)重啓tomcat,一切OK。
需要加入的原因大家可以去研究 $TOMCAT_HOME/webapps/tomcat-docs/config/http.html下的這個文件就可以知道原因了。需要注意的是:這 個地方如果你要是用UTF-8的時候在傳遞的過程中在Tomcat中也是要出現亂碼的情況,如果不行的話就換別的字符集。
(四) JSP頁面上有中文,按鈕上面也有中文,但是通過服務器查看頁面的時候出現亂碼:
解 決的辦法是:首先在JSP文件中不應該直接包含本地化的消息文本,而是應該通過<bean:message>標籤從 Resource Bundle中獲得文本。應該把你的中文文本放到Application.properties文件中,這個文件放在WEB- INF/classes/*下,例如我在頁面裏有姓名,年齡兩個label,我首先就是要建一個Application.properties,裏面的內 容應該是name=”姓名” age=”年齡”,然後我把這個文件放到WEB-INF/classes/properties/下,接下來根據 Application.properties文件,對他進行編碼轉化,創建一箇中文資源文件,假定名字是 Application_cn.properties。在JDK中提供了native2ascii命令,他能夠實現字符編碼的轉換。在DOS環境中找到你 放置Application.properties的這個文件的目錄,在DOS環境中執行一下命令,將生成按GBK編碼的中文資源文件 Application_cn.properties: native2ascii –encoding gbk Application.properties Application_cn.properties 執行以上命令以後將生成如下內容的Application_cn.properties文件:name=/u59d3/u540d age=/u5e74 /u9f84,在Struts-config.xml中配置:<message-resources parameter= "properties.Application_cn"/>。到這一步,基本上完成了一大半,接着你就要在JSP頁面上寫<% @ page language="java" contentType="text/html;charset=GBK" %>,到名字的那個 label是要寫<bean:message key=”name”>,這樣的化在頁面上出現的時候就會出現中文的姓名,年齡這個也是一樣,按鈕上漢字的處理也是同樣的。
(五) 寫入到數據庫是亂碼:
解決的方法:要配置一個filter,也就是一個Servelet的過濾器,代碼如同第二種時候一樣。
如果你是通過JDBC直接鏈接數據庫的時候,配置的代碼如下:jdbc:mysql://localhost:3306/workshopdb?useUnicode=true&characterEncoding=GBK,這樣保證到數據庫中的代碼是不是亂碼。
如 果你是通過數據源鏈接的化你不能按照這樣的寫法了,首先你就要寫在配置文件中,在tomcat 5.0.19中配置數據源的地方是在C:/ Tomcat 5.0/conf/Catalina/localhost這個下面,我建立的工程是workshop,放置的目錄是webapp下面, workshop.xml的配置文件如下:
<!-- insert this Context element into server.xml -->
<Context path="/workshop" docBase="workshop" debug="0"
reloadable="true" >
<Resource name="jdbc/WorkshopDB"
auth="Container"
type="javax.sql.DataSource" />
<ResourceParams name="jdbc/WorkshopDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>url</name>
<value><![CDATA[jdbc:mysql://localhost:3306/workshopdb?useUnicode=true&characterEncoding=GBK]]></value>
</parameter>
</ResourceParams>
</Context>
粗 體的地方要特別的注意,和JDBC直接鏈接的時候是有區別的,如果你是配置正確的化,當你輸入中文的時候到數據庫中就是中文了,有一點要注意的是你在顯示 數據的頁面也是要用<%@ page language="java" contentType="text/html;charset= GBK" %>這行代碼的。需要注意的是有的前臺的人員在寫代碼的是後用Dreamver寫的,寫了一個Form的時候把他改成了一個jsp,這樣有一個地方 要注意了,那就是在Dreamver中Action的提交方式是request的,你需要把他該過來,因爲在jsp的提交的過程中緊緊就是 POST和GET兩種方式,但是這兩種方式提交的代碼在編碼方面還是有很大不同的。