java过滤器
概念
- 是处于客户端与服务器目标资源之间的一道过滤技术
作用
- 执行定位在Servlet之前,客户端发送请求时,会先经过Filter,再到达目标Servlet中;响应时,会根据执行流程再次反向执行Filter
- 可以解决多个Servlet其共性代码冗余问题
实现
import javax.servlet.Filter;
//@WebFilter(value="/t"):精确匹配
//@WebFilter(value="*.html"):后缀匹配
//@WebFilter(value="/*"):匹配项目中任一路径
@WebFilter(value="/t")
public class MyFilter implements Filter{
public void doFilter(ServletRequest servletRequest,ServletResponse servletRespones,FilterChain filterChain){
System.out.println("--请求之前拦截信息--");
//让请求继续执行下一步
filterChain.doFilter(servletRequest,servletRespones);
System.out.println("响应成功结束过滤器")
}
}
@WebServlet(name="TargetServlet",value="/t");
public class TargetServlet extends HttpServlet{
protected void doPost(HttpServletResquest request,HttpServletResponse response){
System.out.println("请求拦截后Target");
}
protected void doGet(HttpServletResquest request,HttpServletResponse){
doPost(request,response);
}
}
配置
-
在自定义Filter类上使用注解@WebFilter(value="/目标路径")
-
xml配置(项目下的web中的web.xml文件)
<filter> <filter-name>过滤器xml配置(名称)</filter-name> <filter-class>过滤器类全称(位置路径)</filter-class> </filter> <!--映射路径配置--> <filter-mapping> <filter-name>过滤器xml配置(名称)</filter-name> <!--过滤的URL路径--> <url-pattern>/*</url-pattern> </filter-mapping>
过滤器链及优先级
-
过滤器链
客户端对服务器请求之后,服务器调用Servlet之前会执行一组(多个过滤器),那么这组过滤器就为过滤器链
-
优先级
- 如果为注释的话,是按照类全名称的字符串顺序决定作用顺序
- 如果web.xml,按照filter-mapping注册顺序,从上往下
- web.xml配置高于注释方式
- 如果注释和web.xml同时配置,会创建多个过滤器对象,造成过滤多次
应用案例
- 中文乱码预处理应用
@WebFilter(value="/*")
public class EncodingFilter implements Filter{
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain){
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest,servletResponse);
}
}
- 登录权限判断
@WebFilter(value="/*")
public class CheckFilter implements Filter{
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain){
//向下转型
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response =(HttpServletResponse)ServletResponse;
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
if(user!=null){
filterChain.doFilter(request,response);
}else{
response.sendRedirect(request.getContextPath()+"login.html");
}
}
}