过滤器在Servlet2.3中规范的,能够对Servlet容器传给当前web组件的ServletRequest和ServletResponse对象进行检查和修改,即“过滤”处理的功能。
和过滤器相关的接口和类,一共有三个接口,分别是Javax.Servlet.Filter、Javax.Servlet.FilterChain、Javax.Servlet.FilterConfig 三个接口;
创建自定义的过滤器需要实现Javax.Servlet.Filter 接口,该接口定义了三个方法,接口源码如下:
package javax.servlet;
import java.io.IOException;
public interface Filter {
public void init(FilterConfig filterConfig) throws ServletException;
public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException;
public void destroy();
}
Javax.servlet.FilterChain接口:
package javax.servlet;
import java.io.IOException;
public interface FilterChain {
public void doFilter ( ServletRequest request, ServletResponse response ) throws IOException, ServletException;
}
Javax.servlet.FilterConfig 接口:
package javax.servlet;
import java.util.Enumeration;
public interface FilterConfig {
//获取过滤器的名字
public String getFilterName();
//获取当前应用上下文
public ServletContext getServletContext();
//获取在web.xml文件中指定name的参数值
public String getInitParameter(String name);
//获取所有的参数名
public Enumeration getInitParameterNames();
}
自定义的过滤器的类只需要实现Filter接口即可。
如下的代码将请求中的编码设置为GBK中文编码,在web.xml中已经设定参数为:
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.longweir.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
针对所有的web请求,该过滤器都有效,过滤器将读取在文件中设置的encoding参数的值设定请求的编码为“GBK”。所以在文件中不再使用request.setCharacterEncoding("GBK")了。
过滤器的类EncodingFilter 如下:
package com.longweir;
//此过滤器对传递的参数实行过滤
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.http.HttpSession;
public class EncodingFilter implements Filter {
private String encode="ISO8859-1";
private FilterConfig config=null;
public void destroy() {
config=null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encode);
//获取过滤器名并保存在application属性中
String filtername=this.config.getFilterName(); //获取过滤器名
if (filtername!=null){
this.config.getServletContext().setAttribute("filtername",filtername);
}
chain.doFilter(request,response);
}
public void init(FilterConfig config) throws ServletException {
this.config=config;
String s=this.config.getInitParameter("encoding");
if (s!=null){
this.encode=s;
}else{
this.encode="GBK"; // 如果没有获取到参数 则自动校正为GBK
}
}
}
则在当前应用中,所有的web请求都自动将设置编码为GBK了。
可以写一个jsp来验证一下即可。