在Spring MVC中,自定义拦截器可以用于拦截请求并在其处理之前或之后执行一些逻辑。同时,自定义异常处理可以帮助我们更优雅地处理和响应错误情况。
以下是一个简单的自定义拦截器和异常处理器的示例:
自定义拦截器:
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 在请求处理之前执行的逻辑
return true; // 如果返回false,则停止流程,api不会被调用
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// 在请求处理之后,视图被渲染之前执行的逻辑
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// 在整个请求结束之后执行的逻辑
}
}
自定义异常处理器:
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// 创建ModelAndView对象,将之设置为错误视图,并添加错误信息
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error", ex.getMessage());
modelAndView.setViewName("error"); // 假设有一个名为error的视图用于显示错误信息
return modelAndView;
}
}
在Spring MVC配置中添加自定义拦截器和异常处理器:
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());
}
@Override
public void configureHandlerExceptionReso