BasicCoder
BasicCoder

Reputation: 1681

How to create an interceptor for annotation @Controller

I joined an existing project who use 2 mechanisms for the front-end with spring mvc:

Now I found an interceptor:

@Aspect
public class RequestMonitor {

    @Autowired
    private RequestMonitorService requestMonitorService;

    @Before("execution(* org.springframework.web.servlet.mvc.Controller+.handleRequest(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse))"
            + "&& args(request,response)")
    public void storeUserAccess(HttpServletRequest request, HttpServletResponse response) {
        requestMonitorService.storeUserAccess(request);
    }
}

who catch all requests from org.springframework.web.servlet.mvc.Controller (mechanism A)

How can I adapt to intercept all other controllers with annotations "@Controller": org.springframework.stereotype.Controller (mechanism B)

Upvotes: 1

Views: 2996

Answers (1)

ant
ant

Reputation: 22948

You have the HandlerInterceptorAdapter class. You can extend it and make use of the methods in your subclass :

public boolean preHandle(HttpServletRequest request, 
        HttpServletResponse response, Object handler) throws Exception

public void postHandle(
        HttpServletRequest request, HttpServletResponse response, 
        Object handler, ModelAndView modelAndView)
        throws Exception

And you need to register your interceptor i.e:

<mvc:interceptors>
        <bean class="my.fully.qualified.package.RequestInterceptor" />
</mvc:interceptors>

Upvotes: 3

Related Questions