SpringMVC拦截器用法(验证用户是否登录)

这是controller类的方法

@RequestMapping("/login") 
public String login(Model model)throws Exception{ 
  return "login";
   }   
//登陆提交 //userid:用户账号,pwd:密码 
@RequestMapping("/loginsubmit")
public String loginsubmit(HttpSession session,String userid,String pwd)throws Exception{ 
   
 //向 session 记录用户身份信息 
  session.setAttribute("activeUser", userid);  
  return "redirect:/main.jsp"; } 
  //退出
@RequestMapping("/logout") 
public String logout(HttpSession session)throws Exception{    
 //session 过期 
  session.invalidate();   
  return "redirect:index.jsp"; 
   } 

拦截器的类代码必须实现HandlerInterceptor类

public class LoginInterceptor implements HandlerInterceptor{ 
 
 @Override 
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception { 
  //如果是登录页面则放行   
  if(request.getRequestURI().indexOf("login.action")>=0){ 
              return true; 
    } 
  HttpSession session = request.getSession(); 
  //如果用户已登录也放行   
  if(session.getAttribute("user")!=null){ 
     return true; 
       } 
  //用户没有登录挑战到登录页面  
    request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);  
 return false;  
 } }

你可能感兴趣的:(session,jsp,java,spring)