Submission / response interception in Spring MVC 3

I am new to Spring MVC 3 and I understand the basic concepts. I can do simple things like creating controllers and services and views. However, I did not raid a more developed territory. So I apologize if this question seems silly (or impossible).

I am wondering if there is a way to intercept the view and / or response and change it before it is sent to the client? I can imagine how Spring binds data to form elements in the output to the client. What I would like to do is check the annotations of the elements in the domain class and change the presentation according to these annotations. This will require entering new code (HTML or Javascript) in response.

UPDATE

As I thought about this a bit more, I realized that the final rendering is done by JSP. Therefore, I assume that the question is whether there is a way to intercept the model before it moves to the page and find out the annotations on the bean to which the data is attached.

Is there any way to do this?

+4
source share
2 answers

The class you're probably looking for is org.springframework.web.servlet.HandlerInterceptor . You can implement the postHandle method on this interface and, as the signature suggests, have access to both the request and the response, as well as the object map of the model that your controller created. (and the controller itself, which is the Object handler parameter.)

You enable them by adding them to the handler mapping in the dispatcher servlet.

 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <bean class="a.package.MyHandlerInterceptor"/> </list> </property> </bean> 

By the way, the binding is actually performed inside the HandlerAdapter, which finds the controller methods and calls them, this is not an interceptor.

Edit: To answer your editing, yes, this is where you have a chance to capture the model object and work with it more after the controller is done, but before it proceeds to JSP rendering. That way you can do something like adding myCustomScript to ModelMap and toss ${myCustomScript} in the <head> your jsp, get the backing object from ModelMap and check it, etc. Etc.

+7
source

Yes, there are actually several ways:

  • spring mvc interceptors (find them in mvc docs ) - you can define preHandle / postHandle and apply the interceptor to multiple controllers.
  • spring aop - determine the aspect that should be performed before / after the methods of this controller
  • servlet filters are the least desirable option since it is not integrated with spring - you cannot enter dependencies.
+4
source

Source: https://habr.com/ru/post/1316322/


All Articles