如何在SpringBoot中配置拦截器,实现登录拦截?

前言:必要的说明

  • 拦截器特性的变化

    Spring4时代,拦截器的定义是:动态拦截Action调用的对象的组件

    Spring5时代,拦截器不光能够拦截动态资源,也会拦截静态资源

  • 配置方法的变化

    在SpringMVC中,需要的是在mvc.xml中配置拦截器

    在SpringBoot中,需要的是在WebMvcConfigurer中配置拦截器

  • 声明拦截器的新方式

    在Java7的时候,通过继承HandlerInteceptorAdapter来声明一个拦截器

    在Java8中,由于可以直接空实现,所以可以直接实现HandlerInteceptor接口,而不用再在去继承HandlerInteceptorAdapter了,也就是说原先的适配器其实没有必要再去使用了

以下是拦截器的配置使用,所有配置均按照最新的来配置

  • 拦截器的声明
public class CheckLoginInteceptor implements HandlerInteceptor{

	@Override
	public void preHandle(HttpServletRequest req,HttpServletResponse resp,Object handler){
		
		//由于Spring5的新特性会拦截静动态资源,所以
		if(handler instanceof HandlerMethod){
			//判断session中是否有对象
			//UserContext为自设工具类,主要是从session中取对象用的
			User user = UserContext.getCurrentUser();
			if(!Optional.ofNullable(user).isPresent()){
				resp.sendRedirect("/login.html");
				return false;
			}
		}
		//其他情况放行
		return true;
	}
}
  • 拦截器的配置
@SpringBootApplication
@Import(CoreConfig.class)
@PropertySource("classpath:application.properties")
public class WebSiteApplication implements WebMvcConfigurer{
	
	//此处对拦截器进行注册,这里需要拦截器的一个对象
	//以及配置拦截目录,以及例外目录
	public void addInteceptors(InteceptorRegistry registry){
		registry.addInteceptor(new CheckLoginInteceptor())
		           .addPathPatterns("/**")
		           .excludePathPatterns("/login.html","/login");
	}

	public static void main(String args[]){
		SpringBootApplication.run(WebSiteApplication.class,args);
	}
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值