Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code before controller in Spring Boot application is called

I need to do some work before the controller in my Spring Boot application is called. Is it possible to only intercept the call to my controller?

I know I can achieve this with intercepting the http request or register a filter but then I would have to deal with URI pattern so that the code is only executed once.

It is enough to have my code executed just before the controller is called.

like image 954
T3rm1 Avatar asked Mar 02 '26 00:03

T3rm1


2 Answers

Is it possible to only intercept the call to my controller?

You can define an interceptor to only intercept calls on a specific uri/controller.

This is done by adding your interceptor this way:

registry.addInterceptor(new MyInterceptor()).addPathPatterns("/your/uri");

The complete code:

@Configuration
public class AnnotationSecurityConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/your/uri");
    }
}

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        System.out.println("afterCompletion");
    }
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("postHandle");
    }
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        System.out.println("preHandle");
        return true;
    }
}
like image 105
alexbt Avatar answered Mar 03 '26 13:03

alexbt


I have used for such problem the Spring Aspect concept here is some short example:

@Component
@Aspect
public class MyAspect {


    private final static String pointcutExpr = "execution(* com.example.myApp.myMethod(..)) || execution(* com.example.myApp.mySecondMethod(..))";

    @Before(pointcutExpr)
    public void doSomethingBefore(JoinPoint joinPoint) throws Exception {

        //here your code
    }
}

Here myMethod and mySecondMethod represents the methods that you want to execute code before them, I hope that helps

like image 33
Tano Avatar answered Mar 03 '26 14:03

Tano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!