AbstractInterceptor
是 Spring AOP(面向切面編程)中的一個核心接口,它允許開發(fā)者定義在方法調(diào)用前后執(zhí)行的代碼。要定制 AbstractInterceptor
的行為,你需要實現(xiàn)以下幾個關(guān)鍵方法:
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
:
true
,則目標方法會被執(zhí)行;如果返回 false
,則目標方法不會被執(zhí)行,并且會直接返回響應(yīng)。postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
:
afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
:
下面是一個簡單的 AbstractInterceptor
實現(xiàn)示例,展示了如何定制攔截行為:
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 {
// 在目標方法執(zhí)行之前進行權(quán)限檢查
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 {
// 在目標方法執(zhí)行之后,但在視圖渲染之前進行日志記錄
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 {
// 在目標方法執(zhí)行完畢之后進行資源清理
System.out.println("After-completion method called for URL: " + request.getRequestURL());
}
private boolean hasPermission(HttpServletRequest request) {
// 實現(xiàn)權(quán)限檢查邏輯
return true; // 示例中默認返回true
}
}
要注冊這個攔截器,你需要在 Spring 配置類中添加一個 HandlerInterceptorRegistry
Bean,并將其與你的攔截器實現(xiàn)關(guān)聯(lián)起來:
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
中的方法就會按照你定義的順序執(zhí)行。