解決亂碼問題的最佳解決方式:
1.將資料庫的編碼方式設成UTF-8。
2.struts2預設的編碼方式為UTF-8。即struts.i18n.encoding=UTF-8。
3.將jsp頁面的編碼方式也設為UTF-8。
這樣就省去了每次將字元編碼轉化或過濾的方式了:
1.使用字元編碼的過濾器.
1.1 自訂實現過濾器的方式設定字元編碼
web.xml 中配置
<!-- 配置struts2過濾器 -->
<filter>
<filter-name>struts2.x</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<!-- 配置struts2中文編碼過濾器 -->
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class>com.cs.tb.util.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
package com.cs.tb.util;
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;
/**
* 用於設定 HTTP 要求字元編碼的過濾器,通過過濾器參數encoding指明使用何種字元編碼,用於處理Html Form請求參數的中文問題
*/
public class CharacterEncodingFilter implements Filter {
private FilterConfig filterConfig;
private String encoding = "";
public void destroy() {
filterConfig = null;
encoding = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(encoding != null){
request.setCharacterEncoding(encoding);//設定字元編碼
chain.doFilter(request, response);//將請求和響應轉向下一個連結
}
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = this.filterConfig.getInitParameter("encoding");// 獲得web.xml檔案中的過濾器中的初始化值encoding
}
}
1.2 使用ActionContextCleanUp
web.xml中配置
<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>
2.request.setCharacterEncoding("UTF-8");
3.str = new String(str.getBytes("ISO8859-1"),"UTF-8");