一、什么是Filter过滤器
它是java web的三大组件之一,三大组件分别为:servlet、filter、listener;
它的作用主要是用于拦截请求,过滤响应;拦截请求常见的应用场景有日记记录,权限校验。。。
二、小例子
新建一个类实现Filter类重写doFilter 方法;
public class FilterTest implements Filter {
}
在里面增加拦截逻辑;
public class FilterTest implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
//获取到session
HttpSession session = httpServletRequest.getSession();
Object user = session.getAttribute("user");
if (user == null){
servletRequest.getRequestDispatcher("/index.jsp").forward(servletRequest,servletResponse);
return;
}else{
//让程序继续往下执行
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
}
}
在web.xml中配置Filter的拦截路径与规则;
FilterTest
com.study.FilterTest
FilterTest
/admin/*
三、简单原理图
简单原理图
发布于 2022-11-07 22:27・IP 属地广东