Struts2乱码问题的解决办法

   乱码问题的起因在于数据在web系统的各个层中间传递的时候编码不同,比如页面使用GB18030而中间层使用UTF-8。由于struts2默认使用的就是UTF-8编码,所以在页面如果使用的是其他的编码格式,那么表单提交后就会产生乱码了。

   我们使用过滤器来解决这个问题。

   以页面使用GB18030为例,两个步骤:

   1、在struts.xml中添加:<constant name="struts.i18n.encoding" value="GB18030"/>

   2、编写转码过滤器:

public class CharacterEncodingFilter implements Filter{

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        // TODO Auto-generated method stub
        arg0.setCharacterEncoding("GB18030");
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        
    }

}

 

posted on 2015-07-19 15:59  肥兔子爱豆畜子  阅读(921)  评论(0编辑  收藏  举报

导航