package cn.itcast.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//首先强制转换 将req转换为HttpServlet类的request
HttpServletRequest request = (HttpServletRequest) req;
//获取资源路径
String URI = request.getRequestURI();
//排除资源 如果资源包含这几个路径就放行
if (URI.contains("login.jsp") || URI.contains("LoginServlet") || URI.contains("/css/") || URI.contains("/js/") || URI.contains("/fonts/") || URI.contains("CheckCodeServlet")){
//如果包含就放行
chain.doFilter(req,resp);
}else {
//如果不包含这些资源 需要验证用户是否登录了
//从登录页面获取传到session域对象中的数据 如果不为空 就代表用户登录了 就放行.
Object user = request.getSession().getAttribute("user");
if (user!=null){
chain.doFilter(req,resp);
}else{
//如果没有登录 就跳转到登录界面
request.setAttribute("msg","您尚未登录,请登录");
request.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
}
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
}
|
|