因为需要使用request方法中的getRequestURI()获取资源请求路径,Filter里的request是ServletRequest类型的而getRequsetURI()方法是HttpServletRequest类型的。所以首先需要强制转换。之后,就判断一下是否初始化页面时可以放行,如果未登录用户要访问登陆后才能查看的信息,就跳转到登陆页面,提示用户先登陆,最后再判断是否登录即可。登录了就放行,登录不成功跳转登录页面
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* <p>
*
* </p>
*
* @autor:lzj
* @date:2021/12/13
*/
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
//获取资源请求路径
String uri = request.getRequestURI();
//判断是否包含登录相关资源路径,要注意排除掉css,js,验证码等资源
if (uri.contains("/login.jsp") || uri.contains("/Login") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/index.jsp") || uri.contains("/images/") || uri.contains("/register.jsp")||uri.contains("/Register")) {
//包含放行
filterChain.doFilter(servletRequest, servletResponse);
} else {
//不包含,跳转登陆页面
//从session中获取user
Object user = request.getSession().getAttribute("userId");
if (user != null) {
//登录了放行
filterChain.doFilter(servletRequest, servletResponse);
} else {
//没有登陆,跳转登陆页面
request.setAttribute("msg", "您尚未登录,请登录");
request.getRequestDispatcher("/login.jsp").forward(request, servletResponse);
}
}
}
}