1 创建过滤器Filter进行登录过滤
/**
* 判断当前游览器是否登录的Filter
*
* */
@WebFilter(urlPatterns = {"*.do","*.jsp"})
public class UserLoginFilter 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();
//判断当前请求是否为login.jsp或者login.do,那么就放行
if(uri.indexOf("login.jsp")!=-1||uri.indexOf("login.do")!=-1){
filterChain.doFilter(servletRequest,servletResponse);
}else{
HttpSession session=request.getSession();
Users users = (Users) session.getAttribute(Constants.USER_SESSION_KEY);
if(users!=null){
filterChain.doFilter(servletRequest,servletResponse);
}else
{
request.setAttribute(Constants.REQUEST_MSG,"不登录休想访问");
request.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
}
}
}
@Override
public void destroy() {
}
}
拦截所有的jsp和servlet,但是需要放行登录时候必要的页面。
2 测试结果