美文网首页
Spring boot 拦截器未生效?WebMvcConfigu

Spring boot 拦截器未生效?WebMvcConfigu

作者: Likaiii | 来源:发表于2019-01-07 13:05 被阅读0次

属于菜鸟级别的Learner,最终目的想做下Android开发。

看完了java基础和Android基础,就准备着手敲代码了。本来想着快速用框架搭建个博客,对java web开发及主流框架有个了解即可。直接上手Spring boot,觉得模模糊糊,雾里看花。没有原理性学习和剖析的那种快感。

说下最近困扰我良久的问题吧,使用Spring boot写@configuration 拦截器,遇到个坑,无论如何就是拦截器不启动,除非用Springboot内置的@EnableWebSecurity()。

对@Bean、@Component、@ComponentScan等等注解的真正原理都是一知半解,看着google百度来的Q&A,都是加上@Component、注解下扫描配置路径@ComponentScan什么的,最终都无法解决我遇到的问题。

最后看各技术论坛Q&A,查到有的童靴的代码里是extends WebMvcConfigurerAdapter,有的代码里是implements WebMvcConfigurer。

原来,

Spring boot 2.0之前,一般使用extends WebMvcConfigurerAdapter来实现自定义拦截器。

Spring boot 2.0之后,官方就推荐使用implements WebMvcConfigurer了。

并且,2.0之前,implements WebMvcConfigurer接口是要重写所有方法的。而2.0之后,WebMvcConfigurer接口中的方法都加上了default,只需要重写所需的方法即可。

马上动手,确实解决了拦截器未启动的问题!!!!
1、确定下项目使用的Spring Boot的版本

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/> <!-- 确认下spring boot的版本号在2.0以上-->
</parent>

2、参照官方文档或者各种教程写拦截器

/**
 * 登录配置和检查
 */
@Configuration
public class WebSecurityConfig implements WebMvcConfigurer{
    public final static String SESSION_KEY="username";

    @Bean
    public SecurityInterceptor getSecurityInterceptor(){
        return new SecurityInterceptor();

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(getSecurityInterceptor()).addPathPatterns("/**").excludePathPatterns("/login**","/dologin**");
            

    }

    public class SecurityInterceptor extends HandlerInterceptorAdapter{
        
    
        @Override
        public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
            HttpSession session=request.getSession();
            if(session.getAttribute(SESSION_KEY)!=null){
                System.out.println("test pass");
                return true;
            }
            
            System.out.println("test refuse");
            String url = "login";
            response.sendRedirect(url);
            return false;
        }
    }
}

相关文章

网友评论

      本文标题:Spring boot 拦截器未生效?WebMvcConfigu

      本文链接:https://www.haomeiwen.com/subject/fccurqtx.html