1、filter在web容器中的作用主要有以下这些:
①对用户抛过来的请求进行字符编码上的转换,及为对用户的响应对象填充公用的头信息;
②验证用户的身份是否已经是登录状态和访问权限的控制;
③其它一些想在用户访问之前做的操作
2、使用实例,为请求内容指定编码
①编写自己的filter类EncodingFilter
package com.demo.filter;
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.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
public class EncodingFilter implements Filter{
protected FilterConfig filterConfig = null;
protected String encoding = "";
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
((HttpServletRequest) request).setCharacterEncoding(encoding);
((HttpServletResponse) response).setHeader("Cache-Control","no-cache");
((HttpServletResponse) response).setHeader("Pragma","no-cache");
((HttpServletResponse) response).setDateHeader ("Expires", -1);
((HttpServletResponse) response).setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
}
EncodingFilter类主要实现了Filter接口,实现了destroy, doFilter, init等filter接口中的方法,init方法在web容器加载filter时执行一次,destory在web容器关闭时被调用释放占用的资源,对于每个请求,都会调用一次doFilter过滤方法
②装配到容器当中去
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.demo.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
这样在每次请求过来的时候就可以将请求的内容转换为utf-8的编码了,并且设置响应中内容为不缓存