SpringMVC拦截器配置后端登录校验

创建拦截器的方法有多种,可以继承HandlerInterceptorAdapter类,也可实现HandlerInterceptor接口。接口中有三个方法:

  1. preHandle:在业务处理器处理请求之前被调用。预处理,可以进行编码、安全控制、权限校验等处理,改方法返回布尔值,true则拦截,false则放行。
  2. postHandle:在业务处理器处理请求执行完成后,生成视图之前执行。
  3. afterCompletion:在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。

创建拦截器

它接受一个HttpServletRequest,所以你可以从request中使用getMethod(),getServletPath()等方法进行更精细的拦截。

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(TokenUtils.verify(token)){
            response.getWriter().write("未登入!");
            return true;
        }else{
            //登陆成功,不拦截
            return false;
        }
    }
}

在springmvc.xml中进行配置

<mvc:interceptors>
        <!--后台访问拦截器-->
        <mvc:interceptor>
            <!--拦截所有资源-->
            <mvc:mapping path="/**"/>
            <!--不拦截-->
            <mvc:exclude-mapping path="/login"/>
            <mvc:exclude-mapping path="/downloadShowFile"/>
            <mvc:exclude-mapping path="/tagArray"/>
            <mvc:exclude-mapping path="/publishArticle"/>
            <mvc:exclude-mapping path="/options/config/**"/>
            <!--实现拦截功能的类-->
            <bean class="cn.mashirodever.blog.Interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
</mvc:interceptors>
原文地址:https://www.cnblogs.com/flytree/p/14706547.html