springboot拦截器的拦截配置和添加多个拦截器

在spring2.0之前的版本大部分都采用extends WebMvcConfigurerAdapter,把拦截器配置成一个bean,具体的方法,我不细说,网上一大堆。
而在spring2.0之后,这个extends WebMvcConfigurerAdapter方法就过时了,官方推荐用implements WebMvcConfigurer。其他的还和以前一样。
特别注意的是spring2.0之前的版本在写implements WebMvcConfigurer的时候会重写这个接口里的全部方法,这是不正常的,而在2.0之后,因为接口中默认加了default关键字,所以你可以重写里面的方法,重写几个无所谓。
建议在写拦截器的时候看看pom.xml的springboot父类版本号是多少,一定要在2.0以上,否则会只拦截请求映射,而不拦截页面。

拦截器配置类

<!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
    </parent>
 
 

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("/**");
}
}

 

登陆方法,静态资源,错误页面无需拦截

 多拦截器配置

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    private static final Logger logger =  LoggerFactory.getLogger(InterceptorConfig.class);

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**");
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/css/**","/images/**","/js/**","/login.html");
        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录或者通过excludePathPatterns配置不需要拦截的路径
        //多拦截器配置
    }

    

猜你喜欢

转载自www.cnblogs.com/h-c-g/p/10849633.html
今日推荐