[置顶] Servlet使用注解定义中英文过滤器(Filter)

时间:2022-02-03 18:29:16


package cn.jbit.easybuy.filter;

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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(urlPatterns={"/*"},filterName="EncodeFilter", initParams={@WebInitParam(name="encode",value="UTF-8")})
public class EncodeFilter implements Filter {
        // 字符编码  
        private String encode = null;
       @Override
      public void destroy() {
         encode = null;
      }
 /**
  * 对所有页面设置字符集编码
  */
 @Override
 public void doFilter(ServletRequest request, ServletResponse response,   FilterChain chain) throws IOException, ervletException {
            if(null==request.getCharacterEncoding()){
                  request.setCharacterEncoding(encode);  // 设置request的编码格式
                  response.setCharacterEncoding(encode);  // 设置request的编码格式
                  response.setContentType("text/html;charset="+encode);
             }
            // 设置response字符编码  
            chain.doFilter(request, response);
 }

 @Override

 public void init(FilterConfig config) throws ServletException {
  //获取初始化参数
     String encode =config.getInitParameter("encode");
      if(this.encode == null){
           this.encode =encode;  //查找配置文件中预设的字符集编码
      }
 }

}