SpringMVC进阶(自定义拦截器以及异常处理)

发布于:2024-04-30 ⋅ 阅读:(29) ⋅ 点赞:(0)

在 Spring MVC 中,自定义拦截器和异常处理是常见的高级用法,可以帮助你在应用程序中实现更灵活的请求处理和异常管理。下面我将为你介绍如何自定义拦截器和异常处理,并提供详细的代码示例。

自定义拦截器

拦截器可以在请求处理之前或之后执行特定的逻辑,比如记录日志、权限验证等。要自定义一个拦截器,你需要实现 HandlerInterceptor 接口,并覆盖其中的方法。通常,一个拦截器包含以下方法:

  • preHandle(HttpServletRequest request, HttpServletResponse response, Object handler): 在请求处理之前被调用,返回 true 则继续执行后续处理,返回 false 则中断请求。
  • postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView): 在请求处理之后、视图渲染之前被调用。
  • afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex): 在视图渲染之后被调用,通常用于资源清理。

下面是一个示例:

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 在请求处理之前执行,可以进行权限验证等操作
        System.out.println("Pre-handle method is called");
        return true; // 返回 true 继续执行后续处理,返回 false 中断请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // 在请求处理之后、视图渲染之前执行
        System.out.println("Post-handle method is called");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) throws Exception {
        // 在视图渲染之后执行,通常用于资源清理
        System.out.println("After completion method is called");
    }
}

注册拦截器

要在 Spring MVC 中注册自定义的拦截器,你需要在配置类(通常是 WebMvcConfigurer 的实现类)中重写 addInterceptors 方法,并将自定义拦截器添加到拦截器链中。

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

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor())
                .addPathPatterns("/**"); // 可以指定拦截的路径
    }
}

异常处理

在 Spring MVC 中,可以通过 @ControllerAdvice@ExceptionHandler 来实现全局异常处理。@ControllerAdvice 注解的类可以处理所有控制器抛出的异常。

下面是一个简单的异常处理示例:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        // 自定义异常处理逻辑,返回适当的 HTTP 状态码和错误消息
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

在上面的示例中,@ExceptionHandler 注解用于指定处理的异常类型,这里是 Exception.class,表示处理所有类型的异常。你可以根据需要指定特定的异常类型进行处理。

以上是关于自定义拦截器和异常处理的基本介绍和示例代码。你可以根据具体的需求和业务场景来进一步扩展和定制这些功能。


网站公告

今日签到

点亮在社区的每一天
去签到