springBoot寫攔截器遇見的坑,不攔截頁面的問題

本人在寫springboot攔截器的時候遇見的一系列問題
  1. 在spring2.0之前的版本大部分都採用extends WebMvcConfigurerAdapter,把攔截器配置成一個bean,具體的方法,我不細說,網上一大堆。
  2. 而在spring2.0之後,這個extends WebMvcConfigurerAdapter方法就過時了,官方推薦用implements WebMvcConfigurer。其他的還和以前一樣。
  3. 特別注意的是spring2.0之前的版本在寫implements WebMvcConfigurer的時候會重寫這個接口裏的全部方法,這是不正常的,而在2.0之後,因爲接口中默認加了default關鍵字,所以你可以重寫裏面的方法,重寫幾個無所謂。
  4. 建議在寫攔截器的時候看看pom.xml的springboot父類版本號是多少,一定要在2.0以上,否則會只攔截請求映射,而不攔截頁面。
    one.
<!-- Spring Boot 啓動父依賴 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.6.RELEASE</version>
	</parent>

two.

package com.dsco.interceptor;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
 * Created by fanclys on 2018/2/23 16:36:16
 * 攔截器配置
 */
@Configuration
public class WebSecurityConfig implements WebMvcConfigurer{
    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return  new SecurityInterceptor();
    }
    private class SecurityInterceptor extends HandlerInterceptorAdapter {
    	 @Override
         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws IOException{
             HttpSession session = request.getSession();
             //判斷是否已有該用戶登錄的session
             if(session.getAttribute("username") !=null){
                 return  true;
             }else {
            	 System.out.println("沒有session");
            	 response.sendRedirect("http://localhost:8080/login.html");
            	 return false;
             }
         }
    }
    @Override
    public  void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //排除配置
        addInterceptor.excludePathPatterns("/userLogin","/css/**","/images/**","/js/**","/login.html");
        //攔截配置
        addInterceptor.addPathPatterns("/**");
    }
}

本人花了6個小時在網上找盡各種辦法,還是不行。幸虧我之前寫過一個,才發現版本號的問題,希望大家遇見這個問題,特別注意。謝謝
本人不才,僅供參考。
Fanclys 2018年11月27日 15:45:12

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章