T3rm1
T3rm1

Reputation: 2532

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.

Upvotes: 3

Views: 9614

Answers (2)

alexbt
alexbt

Reputation: 17045

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;
    }
}

Upvotes: 4

Tano
Tano

Reputation: 1377

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

Upvotes: 1

Related Questions