springboot使用拦截器

博客介绍了使用注解@Configuration配置拦截器的方法,同时提及了拦截器的创建相关内容,属于后端开发中配置和创建拦截器的信息技术知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用注解@Configuration配置拦截器

// 拦截器配置类
@Configuration
//老点的版本继承WebMvcConfigurerAdapter 
public class IntercepptorConfig implements WebMvcConfigurer {

	/**
	 * 注入自定义拦截器
	 * 
	 * @Title: addInterceptors
	 * @Description:重写这个方法,配置需要拦截的路径
	 * @author OnlyMate
	 * @param registry
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 拦截所有请求
		registry.addInterceptor(new CoustomerSessionInterceptor()).addPathPatterns("设置拦截的路径");
		WebMvcConfigurer.super.addInterceptors(registry);
	}
}

拦截器的创建

@Component
public class CoustomerSessionInterceptor implements HandlerInterceptor {
	// 请求之前调用
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if(request.getSession().getAttribute("customerSession") == null) {
			response.sendRedirect("/house/show/loginView");
			return false;
			
		}else {
			return true;
		}
	}
 // 请求之后被调用,但是在试图被渲染之前(controller方法调用之后)
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
   // 在整个请求处理之后,也就是渲染对应试图之后(主要是进行资源清理工作,如:缓存,垃圾回收)
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值