How to run common code for most requests in my Spring MVC web application?

i.e.

I have various URLs mapped using Spring MVC RequestMapping

@RequestMapping(value = "/mystuff", method = RequestMethod.GET) @RequestMapping(value = "/mystuff/dsf", method = RequestMethod.GET) @RequestMapping(value = "/mystuff/eee", method = RequestMethod.GET) 

etc.

I want to follow some general steps up to about 90% of my queries. These are several controllers.

Is there any way to do this without delving into AOP? And if I need to use aspects, any recommendations on how to do this ?!

Thanks!

Additional Information:

To start certain protection for a specific application, we are tied to the parental security setting, which we need to read and call, and then we need to access the cookie before some of our calls, but not all.

+6
source share
3 answers

The interceptor is the solution. It has preHandler and postHandler methods that will be called before and after each request, respectively. You can connect to each HTTPServletRequest object, as well as skip a few by digging it.

Here is a sample code:

 @Component public class AuthCodeInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // set few parameters to handle ajax request from different host response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); response.addHeader("Access-Control-Max-Age", "1000"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Cache-Control", "private"); String reqUri = request.getRequestURI(); String serviceName = reqUri.substring(reqUri.lastIndexOf("/") + 1, reqUri.length()); if (serviceName.equals("SOMETHING")) { } return super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { super.postHandle(request, response, handler, modelAndView); } } 
+3
source

The HandlerInterceptor.preHandle () method gives you access to the request and response, as well as to the target handler. In Spring 3.1, which will be of type HandlerMethod, which gives you access to the class and method of the target controller. If this helps you to try to exclude entire classes of controllers by type name, which will be strongly typed and will not indicate explicit URLs.

Another option would be to create an interceptor mapped to a set of URL patterns. See the section on configuring Spring MVC in the reference documentation.

+1
source

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


All Articles