struts2 中文亂碼的處理方法分享。本站提示廣大學習愛好者:(struts2 中文亂碼的處理方法分享)文章只能為提供參考,不一定能成為您想要的結果。以下是struts2 中文亂碼的處理方法分享正文
合適情形 -> 從jsp傳入到action時的亂碼情形,這裡以GBK為例
1.樹立一個用於轉換編碼的filter
文件地位舉例:src.util.SetCharacterEncodingFilter.java
package 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;
import javax.servlet.UnavailableException;
/**
* Example filter that sets the character encoding to be used in parsing the
* incoming request
*/
public class SetCharacterEncodingFilter implements Filter {
/**
* Take this filter out of service.
*/
public void destroy() {
}
/**
* Select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
request.setCharacterEncoding("gbk");
// 傳遞掌握到下一個過濾器
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
2.修正web.xml,在struts的FilterDispatcher映照之前添加2個filter
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>util.SetCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<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>
</web-app>
3.你的JSP頭應當有
<%@ page language="java" pageEncoding="GBK"%>
4.在struts.xml中修正默許的編碼設定
<struts>
<constant name="struts.i18n.encoding" value="gbk"></constant>
...
...
...
</struts>
根本上就如許可以處理年夜多傳入的字符亂碼成績
PS:假如是數據庫提取字符亂碼,好比mysql,確認你的數據庫內字符是gbk,而且銜接字符串指定了字符編碼
<property name="url" value="jdbc:mysql://localhost/database?useUnicode=true&characterEncoding=gbk"></property>