【spring】自定义拦截器

本文介绍了如何在Spring MVC中自定义拦截器,包括实现Interceptor接口,用于权限校验、日志记录和统计等功能。同时,文章还探讨了Spring的拦截器,其拦截目标为方法,并给出了配置拦截器的步骤。最后,文章提到了全局异常处理,作为对异常情况的统一管理策略。

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

自定义拦截器



spring mvc 拦截器

实现HandlerInterceptor接口

spring-webmvc包下面,可以获取HttpServletRequestHttpServletResponse等web对象实例。

接口请求时,spring MVC拦截器能够自动拦截接口,做权限校验等操作

使用场景:日志记录,统计,权限认证等

  1. 自定义拦截器,实现HandlerInterceptor接口,重写接口的三个方法
public class LoggerAnnotationInterceptor implements HandlerInterceptor
{
	//目标方法执行前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception
    {
    	//eg:
		if(false){
			return false;
		}
		return true;
    }
    
    //目标方法执行后执行,如果preHandle方法返回false,不会执行到该方法
    @Override
    public void postHandle(
                HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
                throws Exception
    {

    }
    
    //请求完成时执行
    @Override
    public void afterCompletion(
                HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception
    {
		//这里可以实现统一日志记录
    }
}

  1. 配置拦截器
<mvc:interceptors>
   <ref bean="customerSpringMvcInterceptor" />
   <ref bean="loggerAnnotationInterceptor" />
</mvc:interceptors>    

spring 拦截器

实现MethodInterceptor接口

spring-aop包下面,拦截的目标是方法

  1. 自定义拦截器,实现MethodInterceptor接口,重写invoke方法
public class DbAnnotationInterceptor implements MethodInterceptor {
	@Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
         //额外功能,例如方法上加了某个注解@
        if(methodInvocation.getMethod().isAnnotationPresent(*.class)){
            //todo
        }
        return methodInvocation.proceed();
    }
}

  1. 配置
<bean id="dbAnnotationInterceptor"
	class="*.DbAnnotationInterceptor">
</bean>
<aop:config>
    <!--切点,表达式用于匹配目标方法-->
	<aop:pointcut id="dbAnnotionPoint"
			expression="@annotation(*.annotation.Database) " />
    <!--通知器,-->
	<aop:advisor pointcut-ref="dbAnnotionPoint"
			advice-ref="dbAnnotationInterceptor" />
</aop:config>

全局异常处理

使用@RestControllerAdvice

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        if (e instanceof ArithmeticException) {
            return "data exception";
        } else if (e instanceof BusinessException){
            return "business exception";
        } else {
            return "server exception";
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值