java web过滤器处理乱码

时间:2021-12-15 04:42:23

我们在servlet页面中读取前台的数据时  经常会出现乱码问题

而自己每次都要在servlet中使用

?
1
2
3
String encoding="utf-8";
request.setCharacterEncoding(enconding);
response.setCharacterEncoding(enconding);

来进行编码的转换  会很麻烦

所以使用过滤器 我们可以避免这些重复的工作

web.xml配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<filter>
 <filter-name>encodingFilter</filter-name>
 <filter-class>com.scx.filter.Filter</filter-class>
 <!-- 初始化参数 -->
 <init-param>
  <param-name>encoding</param-name>
  <param-value>utf-8</param-value>
 </init-param>
 </filter>
 <!-- filter映射关系 -->
 <filter-mapping>
 <filter-name>encodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

Filter

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.scx.filter;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class Filter implements javax.servlet.Filter{
  //读取过滤器配置文件
  private FilterConfig config;
  public void destroy() {
    // TODO Auto-generated method stub
  }
  public void doFilter(ServletRequest arg0, ServletResponse arg1,
      FilterChain chain) throws IOException, ServletException {
    // TODO Auto-generated method stub
    HttpServletRequest request=(HttpServletRequest) arg0;
    HttpServletResponse response=(HttpServletResponse) arg1;
    String encoding=config.getInitParameter("encoding");
    if(encoding==null||"".equals(encoding)){
      encoding="utf-8";
    }
    request.setCharacterEncoding(encoding);
    response.setCharacterEncoding(encoding);
    chain.doFilter(request, response);
  }
  public void init(FilterConfig arg0) throws ServletException {
    // TODO Auto-generated method stub
    config=arg0;
  }
}

这样的话  在servlet里面读取到的数据就不会出现乱码的情况了

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!

原文链接:http://blog.csdn.net/su20145104009/article/details/53191827