struts2中文问题处理
可是我发现保存的时候中文信息都变成乱码了。我表单页面用的事GBK各式。通过追踪,我发现系统在在提交向model值对象中赋值的时候已经变成乱码了,在以前都是通过在web.xml中加入转码过滤器来解决,在struts2中这部分系统已经接管,我们不好再进行过滤转码。查询了一些资料终于找到答案了。总体解决思路就是重载struts2的FilterDispatcher类,在中间加入中文转码代码.
现在把步骤归结如下
1:编写类GBKFilterDispatcher重载FilterDispatcher过滤器(GBKFilterDispatcher.java附注在最后)
2:修改web.xml中的代码
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
修改为:
<filter>
<filter-name>struts2</filter-name>
<filter-class>
com.misbus.util.GBKFilterDispatcher
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
3.在WEB-INF/classes/struts.xml中加入<constant name="struts.i18n.encoding" value="GBK"/>
(经过本人测试,似乎第三步可以不做,但网上一些资料都这么做了,在此也加上)
附:GBKFilterDispatcher.java文件
package com.misbus.util;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.struts2.dispatcher.FilterDispatcher;
public class GBKFilterDispatcher extends FilterDispatcher {
// 默认的过滤编码使用UTF-8
private static String encoding = "UTF-8";
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
String encodingParam = filterConfig.getInitParameter("encoding");
if (encodingParam != null && encodingParam.trim().length() != 0) {
encoding = encodingParam;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
super.doFilter(request, response, chain);
}
}