JSP+Servlet之间乱码的解决仅仅只需一个Filter过滤器即可,为什么在Struts2.x+Hibernate3.0+Spring2.0(以下简称S2SH)中乱码却解决不了呢?因为在S2SH的整合中,Struts2.x的监听监管了JSP页面与Java代码的咬合,这个监管也包括编码的处理,所以当我们编写了认为万无一失的过滤器之后却失效的原因,我的解决方案如下,在此抛砖引玉,如果有更好的办法和建议,望大家提出来。
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
org.apache.struts2.dispatcher.FilterDispatcher;
public class MyFilter extends FilterDispatcher implements Filter {
private FilterConfig config = null;
private String encoding = null;
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
@Override
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain chain) throws IOException, ServletException
{
if (encoding == null) {
encoding = config.getInitParameter("encoding");
}
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
@Override
public void destroy() {
config = null;
encoding = null;
}
}
这个过滤器和平时所编写不同的是它集成自Struts2.x的FilterDispatcher,另外Web.xml的配置如下:
注意此处的顺序,自己编写的过滤器需要配置在首行
<!-- 解决中文乱码问题 -->
<filter>
<filter-name>encodeFilter</filter-name>
<filter-class>com.custservice.util.MyFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>myfilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Struts2的配置 -->
<filter>
<filter-name>struts2.x</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2.x</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Web.xml配置好后,还需要配置Struts2.x的属性文件,在Struts2.x的资源文件夹中找到Struts.properties修改如下:
### This can be used to set
your default locale and encoding scheme
struts.locale=en_US
struts.i18n.encoding=iso-8859-1
改成
### This can be used to set
your default locale and encoding scheme
struts.locale=zh_US
struts.i18n.encoding=gb2312