使用過濾器、struts2處理亂碼簡析

 


 首先使用比較容易的Filter來處理亂碼:(示例)

ForCharacterFilter.java文件:

package cn.edu.bzu;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ForCharacterFilter implements Filter{
	private String characterEncoding;
	private boolean enabled;
	public void init(FilterConfig config){
		characterEncoding=config.getInitParameter("encoding");
		enabled="true".equalsIgnoreCase(config.getInitParameter("using").trim());
		
	}
	public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException{
		if(enabled||characterEncoding !=null){
			request.setCharacterEncoding(characterEncoding);
			response.setCharacterEncoding(characterEncoding);
		}
		response.getWriter().println(request.getParameter("username"));
		chain.doFilter(request, response);		//執行下一個Filter
	}
	public void destroy(){
		characterEncoding=null;		//銷燬時清空資源
	}

}


web.xml配置文件:

<filter>
	<filter-name>ForCharacterFilter</filter-name>
	<filter-class>cn.edu.bzu.ForCharacterFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
	<init-param>
		<param-name>using</param-name>
		<param-value>true</param-value>
	</init-param>
</filter>
<filter-mapping>
	<filter-name>ForCharacterFilter</filter-name>
	<url-pattern>/cn.edu.bzu/*</url-pattern>
</filter-mapping>

注意:
    頁面編碼方式與Filter編碼方式要一致。如果使用get方式提交表單,還需要修改Tomcat裏面的配置文件
   conf/server.xml

  <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" URIEncoding="ISO-8859-1" useBodyEncodingForURI="true" />

就是設定它的默認編碼集。

上面是使用過濾器的方式處理亂碼:有時候這種方法可能會失效
下面是使用struts中處理亂碼:

中文亂碼,首先要區分是頁面亂碼、action亂碼,還是數據庫亂碼。大致的原理是java使用unicode編碼– >window使用gbk(gb2312的擴展集)–mysql默認使用utf-8(unicode的一種編碼方法),這樣轉來轉去就亂碼了 ^_^。解決方法如下:

1. 在struts2裏面,最好將所有字符都設成utf-8。
<%@ page contentType=”text/html; charset=UTF-8″%>
<%@ page pageEncoding=”UTF-8″ %>

1.1 在jsp頁面設定字符編碼。這邊有必有說明的是如果是jsp+java bean+servlet的方案,中文亂碼很好解決,統一設成gb2312就可以了。

1.2 使用struts框架字符集不能設成gb2312,要改成utf-8。
2. 在struts.properties 添加:
struts.devMode=false
struts.enable.DynamicMethodInvocation=true
struts.i18n.reload=true
struts.ui.theme=simple

struts.locale=zh_CN
struts.i18n.encoding=UTF-8

struts.serve.static.browserCache=false
struts.url.includeParams=none

其中locale、encoding就是字符集的設定了。

3. 在web.xml加個filter

<!– zh-cn encoding –>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

跟上述方法,類似還有在action中設定字符編符.


HttpServletResponse response = null;
response = ServletActionContext.getResponse();
request.setCharacterEncoding(”utf-8″);
response.setContentType(”text/html;charset=utf-8″);

通過上述方法,基本就可以搞定中文亂碼的問題了。當然,也有例外(如web server的版本/數據庫的版本等等)。象在我的一個項目碰到一箇中文亂碼,tomcate5.5是會亂碼的,而在tomcate6中就不會。這邊就涉及到tomcate connector字符的設置了。

<Connector port=”80″ maxHttpHeaderSize=”8192″
maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″
enableLookups=”false” redirectPort=”8443″ acceptCount=”100″
connectionTimeout=”20000″ disableUploadTimeout=”true” URIEncoding=”GBK” />

——————————————————————–

後記之一:在使用struts2時,仍是遇到一種亂碼。後來調試才發現,struts2的web.xml配置是有順序的

在web.xml中EncodingFilter的位置應該在Struts2的FilterDispatcher之前,因爲要先調整字符集,然後進入Action。

按照Struts2的API,filter的順序是
struts-cleanup filter
SiteMesh filter
FilterDispatcher

——————————————————————–

後記之二:這個方法是下下策了,只有在前面的方法都無效時才使用。

在action中直接使用request.getParameter()時;還是出現亂碼。原因分析如下:

1、getParameter()是有帶字符參數的。例:

String s = (String)request.getParameter(”txt”).getBytes(”iso-8859-1 “);

2、String也可以帶有字符參數。

String (byte[] bytes, String charsetName)
構造一個新的 String ,方法是使用指定的字符集解碼指定的字節數組。

例:String s = new String(”中文”,”utf-8″);

3、綜合上述兩點,編寫一個類來完成此項任務

public class ConvertCharacter{

public String Convert(String s){

String result;

byte[] temp ;

try{

temp = s.getBytes(”iso-8859-1″);

result =  new String(temp,”utf-8″);

}

return result;

}

}

=====================================================
希望可以借鑑……


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章