SprinBoot拦截器

本文介绍了SpringBoot中拦截器的基本操作,包括如何声明并注册拦截器以实现对请求的拦截,以及展示了拦截器在记录方法执行时间上的小应用。此外,还提到了AOP拦截器的使用,讲解了添加依赖和编写切面类的步骤。
摘要由CSDN通过智能技术生成

拦截器基本操作

声明一个拦截器类需要实现HandlerInterceptor接口

package com.cn.sola.intercepteor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class Myinterceptor implements HandlerInterceptor{
	
	private Logger log = LoggerFactory.getLogger(Myinterceptor.class);

	//操作前
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		HandlerMethod handlermethod = (HandlerMethod) handler;
		
		log.info("【****** MyInterceptor.preHandle ******】" + handlermethod.getBean().getClass().getSimpleName());
		// 如果返回false表示不继续请求,如果返回true表示继续请求
		return true;
	}
	//正在处理
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		HandlerMethod handlermethod = (HandlerMethod) handler;
		
		log.info("【****** MyInterceptor.postHandle ******】" + handlermethod.getBean().getClass().getCanonicalName());
		
		log.info("【****** MyInterceptor.postHandle ******】" + request.getServletPath());
	}
	//操作后
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		log.info("【****** MyInterceptor.afterCompletion ******】" + "拦截处理完毕");
	}
	
}

在Config配置类注册一下基本拦截器

package com.cn.sola.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.cn.sola.intercepteor.Myinterceptor;

@SuppressWarnings("deprecation")
@Configuration
public class MyWebApplicationConfig extends WebMvcConfigurerAdapter{// 定义MVC配置

	@Override
	public void addInterceptors(InterceptorRegistry registry) {//注解拦截器
		
		registry.addInterceptor(new Myinterceptor()).addPathPatterns("/**");//拦截器路径
		
		super.addInterceptors(registry);
	}
}

运行即可

拦截器小应用 可以获取每个方法的执行时间

package com.cn.sola.intercepteor;

import java.util.Timer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class Myinterceptor implements HandlerInterceptor{
	
	private Logger log = LoggerFactory.getLogger(Myinterceptor.class);
	
	private Long times;
	private Long timee;

	//操作前
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		times=System.currentTimeMillis();
		
		HandlerMethod handlermethod = (HandlerMethod) handler;
		
		log.info("【****** MyInterceptor.preHandle ******】" + handlermethod.getBean().getClass().getSimpleName());
		// 如果返回false表示不继续请求,如果返回true表示继续请求
		return true;
	}
	//正在处理
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		HandlerMethod handlermethod = (HandlerMethod) handler;
		
		log.info("【****** MyInterceptor.postHandle ******】" + handlermethod.getBean().getClass().getCanonicalName());
		
		log.info("【****** MyInterceptor.postHandle ******】" + request.getServletPath());
	}
	//操作后
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		log.info("【****** MyInterceptor.afterCompletion ******】" + "拦截处理完毕");
		
		timee = System.currentTimeMillis();
		
		System.out.println(timee-times+"ms");
	}
	
}

AOP拦截器

首先添加依赖

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
			<version>2.0.3.RELEASE</version>
		</dependency>

编写一个切面类

package com.cn.sola.config;

import java.util.Arrays;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ServiceAspect {//此时定义一个业务层拦截处理
	
	private Logger log = LoggerFactory.getLogger(ServiceAspect.class);

	//切面表达式 环绕
	@Around("execution(* com.cn.sola..service..*.*(..))")
	public Object arroundInvoke(ProceedingJoinPoint ponit) throws Throwable{
		
		//获取传递参数数组
		Object[] args = ponit.getArgs();
		
		this.log.info("【****** Service-Before ******】执行参数" + Arrays.toString(args));
		
		//执行放行
		Object object = ponit.proceed(args);
		
		this.log.info("【****** Service-After ******】执行参数" + object);
		
		return object;
		
	}
}

 

SpringBoot拦截器是一种用于拦截和处理请求的组件。在SpringBoot中,我们可以通过实现`HandlerInterceptor`接口或者继承`HandlerInterceptorAdapter`类来创建自定义的拦截器拦截器可以在请求被处理之前和之后执行一些操作,比如验证用户身份、记录日志等。 在SpringBoot中,拦截器的配置可以通过实现`WebMvcConfigurer`接口来完成。我们可以在`addInterceptors`方法中添加我们自定义的拦截器,并指定拦截的路径。例如,我们可以使用`registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")`来添加一个拦截器,并拦截所有的请求。 拦截器与过滤器的区别在于归属和内容。过滤器属于Servlet技术,而拦截器属于SpringMVC技术。过滤器对所有访问进行增强,而拦截器仅针对SpringMVC的访问进行增强。在SpringBoot中,我们可以通过配置类来添加拦截器,如`WebConfig`和`AdminWebConfig`。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *3* [Springboot——拦截器](https://blog.csdn.net/weixin_51351637/article/details/128058053)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Springboot实现拦截器功能](https://blog.csdn.net/weixin_52875557/article/details/123793361)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值