filter中文乱码过滤

 

软件环境:

win2003

MyEclipse 7.1

apache-tomcat-6.0.20

 

在项目中建立一个类,名称:SetCharacterEncodingFilter

SetCharacterEncodingFilter.java代码如下:

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.UnavailableException;
public class SetCharacterEncodingFilter implements Filter {

  protected FilterConfig filterConfig;
  protected String encodingName;
  protected boolean enable;

  public SetCharacterEncodingFilter() {
    this.encodingName = "";
    this.enable = false;
  }
  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    loadConfigParams();
  }
  private void loadConfigParams() {
    this.encodingName = this.filterConfig.getInitParameter("encoding");
    String strIgnoreFlag = this.filterConfig.getInitParameter("enable");
    if (strIgnoreFlag.equalsIgnoreCase("true")) {
      this.enable = true;
    } else {
      this.enable = false;
    }
  }

  public void doFilter(ServletRequest request, ServletResponse response,
                       FilterChain chain) throws IOException, ServletException {
    if(this.enable) {
      request.setCharacterEncoding(this.encodingName);
    }
    chain.doFilter(request, response);
  }

  public void destroy() {
  }

}

2.在包资源管理器中双击web.xml文件。

选择 Filters 过滤器,然后点击右边filter-name的add按钮。

在弹出的对话框中,

filter-name:SetCharacterEncodingFilter
filter-class:SetCharacterEncodingFilter

然后单击“完成”。

在随后的“Init Params”栏目右边单击“Add”

Param-Name:encoding
Param-Value:UTF-8

点击完成。

还要在Init Params栏目中添加另一个参数和值。add

Param-Name:enable
Param-Value:true

单击完成。

3.单击web栏中的Filters,在右边的Filters Mappings栏目右边单击add

在弹出的对话框中只填写两个参数,

filter-name:SetCharacterEncodingFilter
URL-Pattern:/*

点击完成,之后保存web.xml配置文件。重启Tomcat后就能生效了。

经过以下处理之后,所有的请求都会被转换成 UTF-8 的编码格式,这样表单中的中文输入也可以正常获取并显示,不必对每个输入项再进行转换编码处理。

网上流行的方法都是直接用记事本打开web.xml文件添加代码,但是我用的MyEclipse 7.1中的web.xml被记事本打开之后有乱码,用记事本编辑之后,MyEclipse 7.1无法正确加载web.xml,工程也无法正常运行了。就出此下策。

切忌 如果发现有时页面的乱码并没有正确转换的话 你一定要保证 filter配置信息在所有servlet配置的上面。
因为 web.xml的读取机制是从上到下读取的所以要保证 filter最先读取 才能启动中文过滤的作用。

发表评论