ssm中配置filter实现对未登录用户的拦截

1、首先自定义myfilter实现Filter接口,其中session中的name在登录校验的时候存入用户的name

 public String check(HttpServletRequest request) throws NullPointerException{
        ModelAndView model=new ModelAndView();
        String name=request.getParameter("username");
        String password=request.getParameter("password");
        User user=userServiceImpl.login(name);
        if(user!=null) {
            if (password.equals(user.getPassword())) {
                HttpSession session=request.getSession();
                session.setAttribute("name",name);
                model.addObject("name", name);
                return "forward:/showallbooks.action";
            }
            else {
                model.addObject("errormsg", "用户名或密码不正确");
                return "faild";
            }
        }
        else {
            model.addObject("errormsg", "登录失败");
            return "faild";
        }
    }
 @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse) response;
        HttpSession session=req.getSession();
        String username=(String)session.getAttribute("name");       //从session中取得用户
        String url=req.getRequestURI();     //取得请求访问的地址
        //判断从session中取得用户是否为空
        if(username==null){
            //判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
            if(url!=null && !url.equals("") && ( url.indexOf("Login")<0 && url.indexOf("login")<0 )) {
                res.sendRedirect(req.getContextPath() + "/login.action");
                return ;
            }
        }
        chain.doFilter(request,response);
        return;
    }

2.在web.xml中

  
  
    myfilter
    cn.filter.MyFilter
  
  
    myfilter
    *.action
  

 

你可能感兴趣的:(filter)