Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Execute code before controller's method is invoked

Tags:

java

spring

Is there any annotation similar to @PreAuthorize or @PreFilter that I can use to run code before a method in the Controller is invoked?

I need to add info to the request context (specific to the method being called) to be then retrieved by the ExceptionHandler.

For example

@RestController
public MyController{

  @UnkwonwAnnotation("prepareContext(request.getAgentId())"){
  public ResponseEntity method1(RequestA requestA) {
    ...
  }

  @UnkwonwAnnotation("prepareContext(request.getUserName())"){
  public ResponseEntity method1(RequestB requestB) {
    ...
  }

}

I could actually just use @PreAuthorize but doesn't feel right

like image 442
algiogia Avatar asked Jan 25 '19 11:01

algiogia


2 Answers

You Can add interceptor for this

Sample Interceptor

public class CustomInterceptor implements HandlerInterceptor {

    
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse  response) {
    //Add Login here 
        return true;
    }
} 

Configuration

@Configuration
public class MyConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");
    }
}

Hope this helps

like image 59
Niraj Sonawane Avatar answered Oct 17 '22 20:10

Niraj Sonawane


Maybe a good option is implement a custom filter that runs every time that a request is received.

You need extend "OncePerRequestFilter" and overwrite the method "doFilterInternal"

public class CustomFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        //Add attributes to request
        request.getSession().setAttribute("attrName", new String("myValue"));

        // Run the method requested by petition
        filterChain.doFilter(request, response);

        //Do something after method runs if you need.

    }
}

After you have to register the filter in Spring with FilterRegistrationBean. If you have Spring security yo need add your filter after security filter.

like image 27
JosemyAB Avatar answered Oct 17 '22 21:10

JosemyAB