使用过滤器统一全站编码

在web开发中,过滤器是一项非常激动人心的技术,它可以对所有的访问进行控制,通过这些特性,我们可以用来实现很多的需求。常见的有记住用户名密码、统一全站编码等等。本文就利用过滤器+装饰器实现统一全站编码做简单的介绍。

首先需要对jsp和servlet中的编码有一定的了解,具体可以看这篇文章:JSP编码以及乱码解决总结。
实现代码如下:

public class EncodingFilter implements Filter{
  // filter初始化参数
  private FilterConfig config ;
  private static Log log = LogFactory.getLog(EncodingFilter.class);

  public void destroy() {
  // do nothing
  }

  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
    // 获取自定义编码
    String encode = config.getInitParameter("encode");
    if (encode == null){
      encode = "utf-8";
    }
    HttpServletRequest req =(HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");
    // 使用装饰器
    MyReq myReq = new MyReq(req);
    chain.doFilter(myReq, resp);
  }

  public void init(FilterConfig filterConfig) throws ServletException {
    this.config = filterConfig;
  }

  /**
   * 装饰器模式
   * @author: xlli
   * @CreateDate: 2016-3-27 上午12:22:01
   * @version: 1.0
   */
  class MyReq extends HttpServletRequestWrapper{
    private HttpServletRequest req;

    public MyReq(HttpServletRequest request) {
      super(request);
      this.req = request;
    }

    @Override
    public String getParameter(String name) {
      // post请求
      if (req.getMethod().equalsIgnoreCase("post")){
        return req.getParameter(name);
      }
      // get请求
      String value = req.getParameter(name);
      if (value == null){
        return null;
      }
      try {
        value = new String(req.getParameter(name).getBytes("iso8859-1"), "utf-8");
      } catch (UnsupportedEncodingException e) {
        log.error(new Date().getTime() + "EncodingFilter编码转化失败",e);
      };
      return value;
    }
  }

}

你可能感兴趣的:(java-web)