当前位置: 代码迷 >> Java Web开发 >> Filter不能过滤URL汉语言参数乱码
  详细解决方案

Filter不能过滤URL汉语言参数乱码

热度:7943   发布时间:2013-02-25 21:12:34.0
Filter不能过滤URL中文参数乱码
这里是我的filter类
Java code
public class SetCharacterEncoding implements Filter{    // 定义编码类型属性    protected String encoding = null;    // 定义接受过滤器参数的对象    protected FilterConfig filterConfig = null;    // 过滤器初始化方法    public void init(FilterConfig filterConfig) throws ServletException    {        this.filterConfig = filterConfig;        this.encoding = filterConfig.getInitParameter("encoding");        //System.out.println("初始化字符编码过滤器");    }    // 过滤器主方法    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException    {        // 若过滤器编码格式不为空则进入设置        if (this.encoding != null)        {            request.setCharacterEncoding(this.encoding);        }        // System.out.println("字符编码过滤器执行前");        // 继续传递请求,执行程序        chain.doFilter(request, response);        // System.out.println("字符编码过滤器执行后");    }    // 过滤器销毁的方法    public void destroy()    {        try        {            Thread.sleep(1000);// 休眠1s        } catch (Exception e)        {            e.printStackTrace();        } finally        {            // System.out.println("字符编码过滤器销毁的方法");        }    }}


web.xml配置
  <!-- 定义字符转换过滤器 -->
  <filter>
  <filter-name>SetCharacterEncoding</filter-name>
  <filter-class>search.filter.SetCharacterEncoding</filter-class>
  <!-- 设置参数名称及参数值 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
  </filter>
  <!-- 映射定义的Filter,设置对所有的请求进行过滤 -->
  <filter-mapping>
  <filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
  </filter-mapping>

传递参数时URL显示 http://localhost:8080/search/Querry?currentPage=1&keywords=j 北
但获取的 关键词:j ??? 这样无法查询数据库了

------解决方案--------------------------------------------------------
这是get提交
http://localhost:8080/search/Querry?currentPage=1&keywords=j 北
如果是get方式提交的话,
虽然还是会到过滤器里面进行过滤,但并不会转码,
而是会由jvm调用tomcate 服务器的server.xml文件里的配置的编码来进行解码

建议试一下:
Java code
String keywords = request.getParameter("keywords");keywords = new String(keywords.getBytes(),"utf-8");
------解决方案--------------------------------------------------------
可以在配置文件中配置filter,然后把filter的都配置好,编码格式一致,应该没问题。
  相关解决方案