JAVA Web项目的编码过滤器

时间:2022-05-25 15:42:52

首先写一个EncodeFilter的过滤类:

package com.djtu.wy.common;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodeFilter implements Filter{

String encoding = null;
     FilterConfig filterConfig = null;

public void destroy() {
      this.encoding = null;
      this.filterConfig = null;
     }

public void doFilter(ServletRequest arg0, ServletResponse arg1,
       FilterChain arg2) throws IOException, ServletException {
      
      HttpServletRequest request = (HttpServletRequest) arg0;
            HttpServletResponse response = (HttpServletResponse) arg1;
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html; charset="+encoding);
           
            arg2.doFilter(arg0,arg1);
     }

public void init(FilterConfig arg0) throws ServletException {
      this.filterConfig = arg0;
      this.encoding = arg0.getInitParameter("encoding");
     }
    }

而后在web.xml文件中进行配置:

<filter>
   <filter-name>EncodeFilter</filter-name>
   <filter-class>com.djtu.wy.common.EncodeFilter</filter-class>
   <init-param>
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
   </init-param>
  </filter>
  
  <filter-mapping>
   <filter-name>EncodeFilter</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>

之后就大功告成啦!