How can I run common code for most requests in my

2020-06-04 05:35发布

问题:

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 run some common action before about 90% of my requests. These are across several controllers.

Is there anyway to do that without delving into AOP? And if I have to use aspects, any guidance on how to do this?!

Thanks!

More info:

It is to run some app specific security - we are chained to a parent security set up, which we need to read and call into, and then need to access a cookie prior to some most of ours calls, but not all.

回答1:

You can use an Interceptor:

http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping



回答2:

Interceptor is the solution. It has methods preHandler and postHandler, which will be called before and after each request respectively. You can hook into each HTTPServletRequest object and also by pass 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:

The HandlerInterceptor.preHandle() method gives you access to the request and response and also the target handler. In Spring 3.1 that will be of type HandlerMethod, which gives you access to the target controller class and method. If it helps you can try excluding entire controller classes by type name, which would be strongly typed and without specifying explicit URLs.

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