java中用过滤器解决字符编码问题

java的web程序经常出现中文乱码的问题,用一个实现了Filter接口的过滤器类可以较好地解决这个问题。

方式一 EncodingFilter

import java.io.IOException;
import javax.servlet.*;

public class EncodingFilter implements Filter {

    private FilterConfig filterConfig = null;
    private String encoding = null;

     @Override
    public void destroy() {
         filterConfig = null;
         encoding = null;
     }

     @Override
    public void doFilter(ServletRequest request, ServletResponse response,
             FilterChain filterChain) throws IOException, ServletException {
        if (request.getCharacterEncoding() == null) {
            if (encoding != null) {
                 request.setCharacterEncoding(encoding);
             }
             filterChain.doFilter(request, response);
         }
     }

     @Override//初始化的时候就去web.xml配置文件中拿到对应编码格式
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
     }
}

web.xml中配置


      EncodingFilter
      EncodingFilter
     
          encoding
          UTF-8
     

 

 
      EncodingFilter
      /*
 

 

方式二

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.*;

public class WordFilter implements Filter {

public void destroy() {
// TODO Auto-generated method stub

}

@SuppressWarnings("unchecked")
public void doFilter(ServletRequest req, ServletResponse res,
  FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request=(HttpServletRequest)req;
  HttpServletResponse response=(HttpServletResponse)res;
  if(request.getMethod().equalsIgnoreCase("get")){//get提交方式
    Enumeration em=request.getParameterNames();
    while(em.hasMoreElements()){
      String name=em.nextElement().toString();
      String[] values=request.getParameterValues(name);
      for(int i=0;i         values[i]=new String(values[i].getBytes("iso-8859-1"),"utf-8");//把所有字符都转换为指定的编码格式
      }
    }
  }else{
    request.setCharacterEncoding("utf-8");
  }
  chain.doFilter(request, response);
}

  public void init(FilterConfig arg0) throws ServletException {
    // TODO Auto-generated method stub

  }

}

web.xml中配置


WordFilter
filter.WordFilter


WordFilter
/*

 

 

转载于:https://www.cnblogs.com/laotan/p/3639359.html

你可能感兴趣的:(web.xml,java)