java web中字符编码的过滤器(Filter - 1)

      建立一个实现Filter接口的类。这个类需要三个方法,分别是:doFilter、initdestroy。doFilter方法包含主要的过滤代码,init方法建立设置操作,而destroy方法进行清除。

package OSChina;

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;


public class FilterDemo implements Filter {

 protected String encoding = null;

 protected FilterConfig filterConfig = null;

 @Override
 public void destroy() {

  this.encoding = null;
  this.filterConfig = null;

 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {

  String encoding = selectEncoding(request);

  request.setCharacterEncoding(encoding);
  response.setCharacterEncoding(encoding);
  chain.doFilter(request, response);

 }

 /**
  * 或得web.xml中初始化参数"encoding"
  */
 public void init(FilterConfig filterConfig) throws ServletException {

  this.filterConfig = filterConfig;
  this.encoding = filterConfig.getInitParameter("encoding");

 }

 protected String selectEncoding(ServletRequest request) {
  return (this.encoding);
 }

}

配置web.xml如下:

<filter>
   <filter-name>Set Character Encoding</filter-name>
   <filter-class>OSChina.FilterDemo</filter-class>
    <init-param>
       <param-name>encoding</param-name>
       <param-value>UTF-8</param-value>
       </init-param>
 </filter>
 <filter-mapping>
    <filter-name>Set Character Encoding</filter-name>
     <url-pattern>/*</url-pattern>
 </filter-mapping>

 

你可能感兴趣的:(filter)