拦截器的使用案例:权限控制

在实际应用中,我们可以使用拦截器来控制权限,比如,这里做一个这样的小功能,先表单提交数据,
拦截器设置输入的用户名到cokies,然后判断用户名为davis用户是否已登录,如果已登录,则可以
访问系统的欢迎界面,否则返回禁止登录的界面

controller

package com.davis.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class permissionInterceptor {
  @RequestMapping("/permission.do")
  public ModelAndView pInterceptor()throws Exception{
      ModelAndView mv = new ModelAndView();
      mv.addObject("welcome","用户登陆成功!");
      mv.setViewName("welcome");
      System.out.println("dao");
      return mv;
  }
}

welcome.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
</head>
<body>
<h2>
  ${welcome}
</h2>
<br>
</body>
</html>

permissionInterception拦截器

package com.davis.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class permissionInterception implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
   Object handler) throws Exception {
      //把传过来的数据放入cookies
      request.getSession().setAttribute("user",request.getParameter("user"));
      String user=(String)request.getSession().getAttribute("user");
      //判断cookies的user值是否不等于davis,如果判断成立,便跳转到错误页面,不再往下进行
      if(!"davis".equals(user)){
          request.getRequestDispatcher("/jsp/fail.jsp").forward(request,response);
      return false;
      }
      //如果判断不成立,再往下进行,跳到handle(Controller)
      return true;
  }
  
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
  ModelAndView modelAndView) throws Exception {
  }
  
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
   Object handler, Exception ex) throws Exception {
  }
}

fail.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
</head>
<body><h2>
  验证失败!
</h2>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="/permission.do" method="post">
  <input type="text" name="user"><br>
   <input type="submit" value="提交">;
</form>
</body>
</html>

SpringMVC.xml

<mvc:interceptors>
      <mvc:interceptor>
          <mvc:mapping path="/**"/>
          <bean class="com.davis.interceptor.permissionInterception"/>
      </mvc:interceptor>
  </mvc:interceptors>