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

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