1. 程式人生 > 其它 >攔截器Interceptor 的使用筆記

攔截器Interceptor 的使用筆記

參考資料

Spring中使用Interceptor攔截器

WebMvcConfigurer 和 HandlerInterceptor 攔截器配置校驗服務

參考視訊:碼匠筆記

目的

在Controller之前實現 遍歷Cookie值,得到token,通過token查詢user物件

		Cookie[] cookies = request.getCookies();
        /*檢查瀏覽器中有沒有我們設定的cookie物件*/
        if(cookies != null && cookies.length != 0){
            for(Cookie cookie : cookies){
                if( "token".equals(cookie.getName())){
                    /*根據 cookie 中我們設定的資料來查詢資料庫中的使用者資訊*/
                    String  token = cookie.getValue();
                    User user = userMapper.findToken(token);
                    if(user != null){
                        /*根據 cookie找到了使用者資訊,把它儲存到session域中*/
                        request.getSession().setAttribute("user", user);
                    }
                    break;
                }
            }
        }

程式碼

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private SessionInterceptor sessionInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /*新增攔截路徑*/
        registry.addInterceptor(sessionInterceptor).addPathPatterns("/**");
    }
}
@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    UserMapper userMapper;

    /**https://www.cnblogs.com/hy928302776/articles/6956747.html
     * preHandle方法是進行處理器攔截用的,顧名思義,該方法將在Controller處理之前進行呼叫,SpringMVC中的Interceptor攔截器是鏈式的,可以同時存在
     * 多個Interceptor,然後SpringMVC會根據宣告的前後順序一個接一個的執行,而且所有的Interceptor中的preHandle方法都會在
     * Controller方法呼叫之前呼叫。SpringMVC的這種Interceptor鏈式結構也是可以進行中斷的,這種中斷方式是令preHandle的返
     * 回值為false,當preHandle的返回值為false的時候整個請求就結束了。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        /*檢查瀏覽器中有沒有我們設定的cookie物件*/
        if(cookies != null && cookies.length != 0){
            for(Cookie cookie : cookies){
                if( "token".equals(cookie.getName())){
                    /*根據 cookie 中我們設定的資料來查詢資料庫中的使用者資訊*/
                    String  token = cookie.getValue();
                    User user = userMapper.findToken(token);
                    if(user != null){
                        /*根據 cookie找到了使用者資訊,把它儲存到session域中*/
                        request.getSession().setAttribute("user", user);
                    }
                    break;
                }
            }
        }
        return true;
    }

    /**
     * 這個方法只會在當前這個Interceptor的preHandle方法返回值為true的時候才會執行。postHandle是進行處理器攔截用的,它的執行時間是在處理器進行處理之
     * 後,也就是在Controller的方法呼叫之後執行,但是它會在DispatcherServlet進行檢視的渲染之前執行,也就是說在這個方法中你可以對ModelAndView進行操
     * 作。這個方法的鏈式結構跟正常訪問的方向是相反的,也就是說先宣告的Interceptor攔截器該方法反而會後呼叫,這跟Struts2裡面的攔截器的執行過程有點像,
     * 只是Struts2裡面的intercept方法中要手動的呼叫ActionInvocation的invoke方法,Struts2中呼叫ActionInvocation的invoke方法就是呼叫下一個Interceptor
     * 或者是呼叫action,然後要在Interceptor之前呼叫的內容都寫在呼叫invoke之前,要在Interceptor之後呼叫的內容都寫在呼叫invoke方法之後。
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 該方法也是需要當前對應的Interceptor的preHandle方法的返回值為true時才會執行。該方法將在整個請求完成之後,也就是DispatcherServlet渲染了檢視執行,
     * 這個方法的主要作用是用於清理資源的,當然這個方法也只能在當前這個Interceptor的preHandle方法的返回值為true時才會執行。
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}