AbstractInterceptor
是 Spring AOP(面向切面编程)中的一个核心接口,它允许开发者定义在方法调用前后执行的代码。要定制 AbstractInterceptor
的行为,你需要实现以下几个关键方法:
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)
:
下面是一个简单的 AbstractInterceptor
实现示例,展示了如何定制拦截行为:
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) throws Exception {
// 在目标方法执行之前进行权限检查
if (!hasPermission(request)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Permission denied");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在目标方法执行之后,但在视图渲染之前进行日志记录
System.out.println("Post-handle method called for URL: " + request.getRequestURL());
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在目标方法执行完毕之后进行资源清理
System.out.println("After-completion method called for URL: " + request.getRequestURL());
}
private boolean hasPermission(HttpServletRequest request) {
// 实现权限检查逻辑
return true; // 示例中默认返回true
}
}
要注册这个拦截器,你需要在 Spring 配置类中添加一个 HandlerInterceptorRegistry
Bean,并将其与你的拦截器实现关联起来:
import org.springframework.context.annotation.Bean;
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 {
@Bean
public CustomInterceptor customInterceptor() {
return new CustomInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(customInterceptor())
.addPathPatterns("/**") // 指定拦截的URL模式
.excludePathPatterns("/login", "/register"); // 指定排除的URL模式
}
}
这样,当有请求匹配到 /**
URL 模式时,CustomInterceptor
中的方法就会按照你定义的顺序执行。