SpringMVC 之 mvc:exclude-mapping 不拦截某个请求

在使用 SpringMVC 是,配置了一个 Session 拦截器,用于拦截用户是否登录,但是用户访问登录页面和注册页面时就不需要拦截了,这时就需要用到这个标签了 <mvc:execlude-mapping />。

代码上来先:

<!-- 配置用于session验证的拦截器 -->
    <!-- 
        如果有多个拦截器满足拦截处理的要求,则依据配置的先后顺序来执行
     -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 拦截所有的请求,这个必须写在前面,也就是写在【不拦截】的上面 -->
            <mvc:mapping path="/**" />
            <!-- 但是排除下面这些,也就是不拦截请求 -->
            <mvc:exclude-mapping path="/login.html" />
            <mvc:exclude-mapping path="/account/login.do" />
            <mvc:exclude-mapping path="/account/regist.do" />
            <bean class="com.msym.cloudnote.interceptors.SessionInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

有一点要注意:

就是上面的【拦截】和【不拦截】,【拦截】的标签要写在上面。

拦截器的代码:

package com.msym.cloudnote.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 判断是否登录的拦截器
 * @author 码上猿梦
 *  http://www.cnblogs.com/daimajun/
 */
public class SessionInterceptor  implements HandlerInterceptor {

    
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        
    }

    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handel) throws Exception {
        HttpSession session = req.getSession();
        // 从session当中获取特定的数据
        Object obj = session.getAttribute("name");
        if (obj == null) {
            // 未登录,重定向到登录页面
            res.sendRedirect(req.getContextPath()+"/login.html");
            return false;
        }
        // 已登录,继续向后调用
        return true;
    }
}
原文地址:https://www.cnblogs.com/daimajun/p/7172208.html