码迷,mamicode.com
首页 > 其他好文 > 详细

Encoding filter 编码过滤器

时间:2016-04-17 06:22:11      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

1、首先编写过滤器,实际上就是继承了filter接口的一个类,实现其中的init  doChain  和destroy方法

技术分享
package com.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;


public class EncoderFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        System.out.println("i defined filter destroy~~~~~~~~~~~~~~~~~~~~~~");
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        // TODO Auto-generated method stub
        arg0.setCharacterEncoding("UTF-8");
        System.out.println("the request encoding is " + arg0.getCharacterEncoding());
        System.out.println("enter myself filter~~~~~~~~~~~~~~~~~~~~~~" + new String(arg0.getParameter("men.name").getBytes(), "GBK"));
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println("i defined filter init~~~~~~~~~~~~~~~~~~~~~~");
    }

    

}
EncoderFilter.java

2、在web.xml文件里面,加入如下代码

技术分享
  <filter>
          <filter-name>encodeFilter</filter-name>
          <filter-class>com.util.EncoderFilter</filter-class>
  </filter>
  <filter-mapping>
          <filter-name>encodeFilter</filter-name>
          <url-pattern>/*</url-pattern>
  </filter-mapping>
web.xml

切记,此代码应该加在struts2的过滤器前面的位置。

这时候访问传汉字应该是没有问题了,可是~~~还是乱码,解决办法:修改tomcat的server.xml文件


<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
里添加上后面3个编码的设置

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
useBodyEncodingForURI="true"
IEncoding="utf-8"
URIEncoding="utf-8"
/>

这时候传汉字就正常了!

 

关于编码,可以使用request.getCharacterEncoding()方法来看请求时采用的是什么编码!

 

Encoding filter 编码过滤器

标签:

原文地址:http://www.cnblogs.com/tengpan-cn/p/5399944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!