16

While writing interceptor for my application I noticed HandlerInterceptor and WebRequestInterceptor here.

I noticed that HandlerInterceptor's method take HttpServletRequest, HttpServletResponse, Object(handler) and other params while WebRequestInterceptor take WebRequest (a wrapper of HttpServletRequest).

But I don't know what is the difference between these two interceptors.

Although seeing Spring API I can guess that WebRequestInterceptor can not commit response while HandlerInterceptor can do that. Please correct me here if I am wrong.

Andreas Jägle
  • 11,632
  • 3
  • 31
  • 31
optional
  • 3,260
  • 5
  • 26
  • 47

1 Answers1

18

With a HandlerInterceptor you can:

  • Change the HttpServletResponse in preHandle method
  • Apply filters based on handler object. For example, you can apply some filters based on presence of some annotations on HandlerMethod
  • Prohibit the execution of the handler by returning false in preHandle method.

HandlerInterceptor can be used for a large field of preprocessing aspects, e.g. for authorization checks, or common handler behavior like locale, theme changes or adding Cache-Control headers. Its main purpose is to allow for factoring out repetitive handler code.

One of the canonical use cases of WebRequestInterceptor is preparing context resources (such as a Hibernate Session) and expose them as request attributes or as thread-local objects. Also, you can modify those context resources after successful handler execution (for example, flushing a Hibernate Session). For example, OpenEntityManagerInViewInterceptor binds a JPA EntityManager to the thread for the entire processing of the request.

Although seeing Spring API I can guess that WebRequestInterceptor can not commit response while HandlerInterceptor can do that. Please correct me here if I am wrong.

WebRequestInterceptor interface is deliberately minimalistic to keep the dependencies of generic request interceptors as minimal as feasible. If you need to change the response, you should use HandlerIntercepter or Filters.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • 1
    Yes , I got this too here: http://docs.spring.io/spring-framework/docs/2.0.8/api/org/springframework/web/context/request/class-use/WebRequestInterceptor.html . But I mean is it only for those purpose ? – optional Feb 27 '16 at 10:29
  • 1
    And in `WebRequestInterceptor` you just can modify the model not response – Ali Dehghani Feb 27 '16 at 10:32
  • Exactly that is what I am asking that's why it does not have any response parameter(**HttpServletResponse**) in its method signature – optional Feb 27 '16 at 10:35
  • 1
    It's by design minimalistic, if you in need to change to response, use `HandlerIntercepter` or `Filter`. – Ali Dehghani Feb 27 '16 at 10:38