Filter过滤器
-
Filter过滤器它是JavaWeb的三大组件之一。三大组件分别是:Servlet程序、Listener监听器、Filter过滤器。
-
Filter过滤器它是JavaEE的规范。也是接口。
-
Filter过滤器它的作用是:拦截请求,过滤响应。
-
拦截请求常见的应用场景有:
- 权限检查
- 日记操作
- 事务管理
- 等
-
要求:在你的web工程下,有一个admin目录。这个admin目录下的所有资源(html页面、jpg图片、jsp文件等等)都必须是用户登录之后才允许访问。
import com.wz.userManager.pojo.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(filterName = "UserCenterFilter",urlPatterns = {"/pages/*"})
public class UserCenterFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)servletRequest;
HttpServletResponse resp= (HttpServletResponse)servletResponse;
HttpSession session = req.getSession();
User username = (User) session.getAttribute("user");
if(username==null){
servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
}
}