Before method for each Controller in Spring Boot

Viewed 552

I want to implement a before method for each controller in Spring Boot. So that the before method is invoked for any REST request.

1 Answers

You can use a Filter to intercept all incoming requests before handling them in the controller:

A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.

You can do something like that in your code:

@Component
public MyLogFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        System.out.println("Requested received and handled before controller");
        chain.doFilter(req, res);
        System.out.println("Code executed after controller");
    }
    ...
}

You can also add logic to bypass the call to the controller if needed. For example if you have an authentication filter and you see that the request is not authenticated you can directly reply with a 401 code without calling the controller.

Related