1. 程式人生 > >struts2 action接收到的引數中文亂碼的問題

struts2 action接收到的引數中文亂碼的問題

中文亂碼,首先要區分是頁面亂碼、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+javabean+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>
糾結了兩三個小時,試過N多中方法,最終還是通過方法2解決的!