java中的过滤器,在网上看到的~~

1. 先新建一个 EncodingFilter.java : 


import java.io.*;
import javax.servlet.*;
public class EncodingFilter implements Filter {
String encoding = null;
FilterConfig filterConfig = null;

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

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

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

2. 然后新建一个web.xml 配置编码过滤器 :

<web-app>
<filter>
   <filter-name>EncodingFilter</filter-name>
   <filter-class>com.filter.EncodingFilter</filter-class>
   <init-param>
    <param-name>encoding</param-name>
    <param-value>gb2312</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>EncodingFilter</filter-name>
   <servlet-name>action</servlet-name> (or <url-pattern>/*.do</url-pattern>)
</filter-mapping>
</web-app>

你可能感兴趣的:(java,Web,xml,servlet)