Spring Bootのインターセプターの作り方はどうですか?
Spring Bootのインターセプターを作成するには、以下の手順に従う必要があります。
- ハンドラーインターセプター
- preHandle()メソッド
- 処理を後処理する
- 処理完了後()
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
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 {
// 在请求处理之前进行调用(Controller方法调用之前)
return true; // 如果返回false,则请求中断
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)
}
}
- WebMvcConfigurerAdapterを日本語で説明するとうれしいです。
- インターセプターを追加する
- 設定
- @EnableWebMvcを有効にする
- オーバーライド
- インターセプターを追加します。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/**");
// 添加自定义拦截器,并设置拦截路径,这里设置拦截所有请求
}
}
これにより、簡単なSpring Bootインターセプターが作成されます。アプリケーションにリクエストが入ると、インターセプターのpreHandle()メソッドが呼び出され、その後、リクエストを中断するかどうかを決定します。リクエスト処理が完了すると、インターセプターのpostHandle()メソッドが呼び出され、ビューのレンダリング前に実行されます。最後に、リクエスト全体が終了すると、インターセプターのafterCompletion()メソッドが呼び出され、リソースのクリーンアップが行われます。