之前使用struts1的時候是通過寫filter來處理亂碼,把寫的filter搬到struts2,配置了WEB.XML發生沒有效果,請求根本就沒有通過filter。原因Struts2在web.html配置了處理action請求的filter:
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
通過這個sturts filter後,在這個struts filter之前或之後配置都是發現處理亂碼的filter不起作用,所以編寫攔截器還是個不錯的解決亂碼的方式。
1、編寫自訂 EncodingIntereptor攔截器
import java.io.UnsupportedEncodingException;import java.util.Iterator;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.StrutsStatics;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class EncodingInterceptor extends AbstractInterceptor { /** * Struts2編碼攔截器 */ @Override public String intercept(ActionInvocation arg0) throws Exception { // TODO Auto-generated method stub ActionContext actionContext = arg0.getInvocationContext(); HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST); System.out.println("Encoding Intercept..."); /** * 此方法體對GET 和 POST方法均可 */ if( request.getMethod().compareToIgnoreCase("post")>=0){ try { request.setCharacterEncoding("GBK"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ Iterator iter=request.getParameterMap().values().iterator(); while(iter.hasNext()) { String[] parames=(String[])iter.next(); for (int i = 0; i < parames.length; i++) { try { parames[i]=new String(parames[i].getBytes("iso8859-1"),"GBK");//此處GBK與頁面編碼一樣 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } return arg0.invoke(); }}
2、Struts.xml配置
下註冊攔截器:
<package> <interceptors> <interceptor name="Encoding" class="com.disaster.util.EncodingInterceptor"></interceptor> <interceptor-stack name="Encode"> <interceptor-ref name="Encoding"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref><!-- 必須引入這個,否則request不會再往下傳--> </interceptor-stack> </interceptors>
3、使用攔截器,可將其設為預設的攔截器
<default-interceptor-ref name="Encode"></default-interceptor-ref>
4、頁面編碼和頁面字元編碼跟設為"UTF-8"。如果頁面是其它編碼,將攔截器中重編碼部分改一下即可。