SpringMVC 拦截器使用说明

spring-content.xml 

<!-- 配置用于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: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;

/**
 * 判断是否登录的拦截器
 */
public class SessionInterceptor  implements HandlerInterceptor {

    @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 { }
@Override public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handel) throws Exception { HttpSession session = req.getSession(); // 从session当中获取特定的数据 Object obj = session.getAttribute("userInfo"); if (obj == null) { // 未登录,重定向到登录页面 res.sendRedirect(req.getContextPath()+"/login.html"); return false; } // 已登录,继续向后调用 return true; } }

  

注:3个方法的调用顺序请查看 https://www.cnblogs.com/wdw31210/p/10535843.html

猜你喜欢

转载自www.cnblogs.com/wdw31210/p/10535829.html