SpringBoot拦截器

前言

平时我们的SSM项目中我们可以使用web.xml配置拦截器,但是我们的springboot项目没有web.xml,所有我们的拦截器就需要自己来配置了。

需要先创建**.****.*****.config.LoginInterceptorConfigurer配置类,实现**WebMvcConfigurer**接口,并添加@Configuration注解,重写其中的addInterceptors()方法以注册拦截器:
@Configuration
public class LoginInterceptorConfigurer  implements WebMvcConfigurer{
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		HandlerInterceptor interceptor = new LoginInterceptor();
		//因为我们下面会拦截所有的路径,这里可以将我们不需要拦截的路径保存到list集合中
		List<String> excludeList = new ArrayList<>();
		excludeList.add("/users/reg");
		excludeList.add("/users/login");
		excludeList.add("/districts/**");
		excludeList.add("/products/**");
		
		excludeList.add("/web/register.html");
		excludeList.add("/web/login.html");
		excludeList.add("/web/index.html");
		excludeList.add("/web/product.html");
		excludeList.add("/web/search.html");
		
		excludeList.add("/bootstrap3/**");
		excludeList.add("/images/**");
		excludeList.add("/css/**");
		excludeList.add("/js/**");
		
		registry.addInterceptor(interceptor)
		.addPathPatterns("/**")
		.excludePathPatterns(excludeList);
	}
}

注意上面的自定义类需要加上@Configuration注解,不然不生效

我们需要自定义**.****.*****.interceptor.LoginInterceptor拦截器类,实现**HandlerInterceptor**接口,并重写preHandle()方法,以决定拦截规则:

public class LoginInterceptor implements HandlerInterceptor {
	
		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
				throws Exception {
			// 从参数request中获取session
			HttpSession session = request.getSession();
			// 判断session中有没有登录信息
			if (session.getAttribute("uid") == null) {
				// 没有登录信息,则重定向到登录页
				response.sendRedirect("/web/login.html");
				// 执行拦截,阻止运行
				return false;
			}
			// 存在登录信息,直接放行
			return true;
		}
		
	}

另外,需要我们在启动类上加上的我们@Configuration注解,在@SpringBootApplication上面下面都无所谓

好了,springboot的拦截器配置基本完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值