Springboot2攔截器設(shè)置(不攔截靜態(tài)資源)

  • 1 springboot2配置攔截器和Springboot配置有所不同,話不多說,showcode。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new SessionHandlerInterceptor());
        interceptorRegistration.excludePathPatterns("/error");
        interceptorRegistration.excludePathPatterns("/static/**");
        interceptorRegistration.excludePathPatterns("/login");

        interceptorRegistration.addPathPatterns("/**");


    }


    private class SessionHandlerInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

            Object user = request.getSession().getAttribute("user");
            if (user == null) {
                try {
                    response.sendRedirect("/login");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;

            }
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
            //controller方法處理完畢后,調(diào)用此方法
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
            //頁面渲染完畢后調(diào)用此方法
        }
    }
}
  • 2 重點在于
 interceptorRegistration.excludePathPatterns("/static/**");

這句會忽略靜態(tài)資源。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,111評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,588評論 19 139
  • 第十四章 父母怎樣才能不被“炒魷魚” 孩子不會反抗成年人---他們反抗的是成年人奪走他們自由的企圖。 1、孩子越來...
    海上明月明閱讀 311評論 0 0
  • 連續(xù)讀完了兩本小說《了不起的蓋茨比》和《月亮與六便士》。拋開小說的其他不講,我特別有興趣對比一下兩本小說里隱含著的...
    宋小song閱讀 557評論 3 3
  • 離開一段時間后我又回歸到這個大家庭,感賞老師們再次的接納,給予我鼓勵和幫助,感賞群內(nèi)的朋友熱情友愛,感賞自己能重新...
    張茹_閱讀 219評論 0 1

友情鏈接更多精彩內(nèi)容