在 Spring Boot 中,您可以使用攔截器(Interceptor)來在請求處理之前或之后執行一些操作。要使用攔截器,請按照以下步驟操作:
HandlerInterceptor
接口的類。例如,創建一個名為 MyInterceptor
的類:import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在請求處理之前執行的操作
System.out.println("preHandle: 請求處理之前");
return true; // 返回 true 表示繼續處理請求,返回 false 則中斷請求處理
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在請求處理之后,但在視圖渲染之前執行的操作
System.out.println("postHandle: 請求處理之后,但在視圖渲染之前");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在請求處理完成后執行的操作,例如關閉資源
System.out.println("afterCompletion: 請求處理完成");
}
}
WebMvcConfig
的配置類,并實現 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 WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注冊攔截器,并為其指定攔截路徑模式
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**") // 攔截所有請求
.excludePathPatterns("/login", "/register"); // 排除特定請求
}
}
現在,您的攔截器已經注冊并配置好了。當用戶訪問應用程序中的任何請求時,MyInterceptor
中的 preHandle
、postHandle
和 afterCompletion
方法將按照順序執行。您可以根據需要修改這些方法以實現您的功能。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。