SpringFrameworkのHandlerInterceptorで共通処理
Spring MVCでのリクエストに対してのアクセスコントロールや認証などの共通処理を
実装する方法は、HandlerInterceptorを利用すると実現可能です。
Servlet Filterでも可能なんですが...。
それで、このHandlerInterceptorは、インターフェイスで、それを実装する必要があります。
この方法を使うと、Controllerの前後で、処理を呼び出すことが可能になります。
HandlerInterceptorには、下記の3つのメソッドが定義されています。
postHandle
ビューのレンダリング完了前に呼ばれるメソッドです。
サーバーサイドMVCで利用可能ですがSPAでは、
ビューのレンダリング等がないので、RestAPIだと呼ばれないようです。
ビューのレンダリング前に何らかの処理を入れたい場合は、 このメソッド内に処理を書きます。
afterCompletion
ビューのレンダリング完了後に呼ばれるメソッドです。
後処理を記述する場合は、このメソッド内に処理を書きます。
サーバーサイドMVC及び、SPAともに呼ばれます。
サーバーサイドMVCは、postHandleに後処理を書きますが、
SPAの場合は、このメソッド内に後処理を書きます。
実際のインターフェイスを実装したクラスを作成して、
必要なメソッド内に共通処理を記述すれば完了です。
public class SampleHandlerInterceptor implements HandlerInterceptor { /** * {@inheritDoc} */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 共通処理を記述する。 return true; } /** * {@inheritDoc} */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception { // 共通処理を記述する。 } /** * {@inheritDoc} */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView view) throws Exception { // 共通処理を記述する。 } }
HandlerInterceptorを実装したクラスを作成しただけでは、利用できません。
Webアプリケーションの設定クラスで、作成したHandlerInterceptorを登録します。
Webアプリケーションの設定クラスは、WebMvcConfigurationSupportを継承して、
@ConfigurationのAOPを付加する必要があります。
@Configuration public class SampleWebApplicationConfiguration extends WebMvcConfigurationSupport { @Bean public SampleHandlerInterceptor sampleHandlerInterceptor() { return new SampleHandlerInterceptor(); } /** * {@inheritDoc} */ @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(sampleHandlerInterceptor()).addPathPatterns("/**") }
最後に、ApplicationContext.xmlにWebアプリケーション設定クラスを設定すれば完了です。
<bean class="com.chronos.configuration.SampleWebApplicationConfiguration"/>