1. 程式人生 > >Spring boot 攔截器、登陸攔截

Spring boot 攔截器、登陸攔截

Springboot專案怎麼使用攔截器

在這裡小小推薦下我的個人部落格

簡書:雷園的簡書

  1. 建立一個攔截器並實現HandlerInterceptor介面
package com.leiyuan.bs.interceptor;

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

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

// 攔截器
public class MyHandlerInterceptor implements HandlerInterceptor {
    /**
     * 攔截(Controller方法呼叫之前)
     *
     * @param request  request
     * @param response response
     * @param o        o
     * @return 通過與否
     * @throws Exception 異常處理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object
            o) throws Exception {
        // TODO 我這裡是通過使用者是否登陸進行攔截,我的使用者資訊儲存在session中,名稱為userSession,大家可以自行實現
        if (request.getSession().getAttribute("userSession") == null) {
            // 攔截至登陸頁面
            request.getRequestDispatcher("/user/toLogin").forward(request, response);
            // false為不通過
            return false;
        }
        // true為通過
        return true;
    }

    // 此方法為處理請求之後呼叫(呼叫過controller方法之後,跳轉檢視之前)
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    // 此方法為整個請求結束之後進行呼叫
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }
}
  1. 建立一個配置類MyHandlerInterceptorConfig並繼承WebMvcConfigurerAdapter類重寫addInterceptors(InterceptorRegistry registry)方法
package com.leiyuan.bs;

import com.leiyuan.bs.interceptor.MyHandlerInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
// 攔截器配置類
@Component
public class MyHandlerInterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	/**
         * 這裡的addPathPatterns("/**")為配置需要攔截的方法“/**”代表所有,而後excludePathPatterns("/user/toLogin")等方法為排除哪些方法不進行		 攔截
         */
        registry.addInterceptor(new MyHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/toLogin").excludePathPatterns
                ("/user/login").excludePathPatterns("/user/toNewUser").excludePathPatterns("/user/newUser");
        super.addInterceptors(registry);
    }
}

  1. 啟動專案即可看到效果了