HandlerInterceptor 自定义拦截器

HandlerInterceptor 自定义拦截器

org.springframework.web.servlet.HandlerInterceptor
创建自定义类

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        // 1.通过request对象获取session对象
        HttpSession session = request.getSession();

        // 2.从session域中获取admin对象
        Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);

        // 3.判断Admin是否为null
        if (admin == null){
            throw new AccessForbiddenException(CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
        }
        // 4.admin不为null返回true放行
        return true;
    }
}

springmvc.xml 配置

    <!--注册拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 配置要拦截的资源  /* 代表一层路径/a  /** 代表多层路径-->
            <mvc:mapping path="/**"/>
            <!-- 配置不拦截的资源 -->
            <mvc:exclude-mapping path="/admin/do/logout.html"/>
            <mvc:exclude-mapping path="/admin/admin-login.html"/>
            <mvc:exclude-mapping path="/admin/do/login.html"/>
            <bean class="org.zrz.crowd.mvc.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
上一篇:SpringBoot使用HandlerInterceptor添加跨域信息头


下一篇:自定义登录拦截器 HandlerInterceptor