访问数据之前要先判断该用户是否登录
package cn.itcast.web.filter;
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("/*")
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//0.强制装换,强转的目的是为了获得HttpHttpServletRequest中获得uri方法
HttpServletRequest request =(HttpServletRequest)req;
//HttpServletResponse response =(HttpServletResponse)resp;
//1.获取资源路径,是为了排除与登录相关的资源
String uri = request.getRequestURI();
//2.判断URI路径是否包含登录相关资源
if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/ccs/") || uri.contains("/js/") || uri.contains("/fonts/") ||uri.contains("/checkCodeServlet")){
//用户就是想登录,直接放行
chain.doFilter(req, resp);
}else{
//如果不包含,需要验证用户是否登录,可以取user 来判断是否登录,
// 因为在做登录页面的时候,用户如果登录成功,我们把user对象已经存入session中
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
if(user != null){
//说明用户已经登录,放行
chain.doFilter(req, resp);
}else{
//说明用户没有登录,跳转到提示界面
request.setAttribute("login_msg","你尚未登录,请登录");
request.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
//chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}