Rohit Taleja
Rohit Taleja

Reputation: 1

How to execute a filter on specific request in spring mvc?


Below is the Filter.

@Component
public class TestFilter extends GenericFilterBean {

@Override
public void doFilter(
  ServletRequest request, 
  ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
    chain.doFilter(request, response);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    System.out.println("token is: "+httpRequest.getHeader("token"));
}    
}

Below is the resource I want to execute above filter for the second request only.

How it can be done, plz help....

@RestController
public class UserResourceImpl implements UserResource {

private final UserDao userDao;
private final AuthenticationService authenticationService;
@Autowired
public UserResourceImpl(final UserDao userDao,final AuthenticationService authenticationService) {
this.userDao = userDao; 
this.authenticationService = authenticationService;
}

@Override
@RequestMapping(method = RequestMethod.POST, value = "/api/user", produces = "application/json")
public ResponseEntity<?> create(final User user) {
    userDao.save(user);
    return new ResponseEntity<>("", HttpStatus.OK);
}

@Override
@RequestMapping(method = RequestMethod.GET, value = "/api/user", produces = "application/json")
public ResponseEntity<?> getUsers(final User user) {


enter code here
    // how to execute the above filter for this request only ?

    return new ResponseEntity<>("", HttpStatus.OK);
}

}

Upvotes: 0

Views: 1963

Answers (1)

Baptiste Beauvais
Baptiste Beauvais

Reputation: 2086

You could try with a HandlerInterceptorAdapter. It works by url and not specific method so it's not exactly what you want but it should work:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //To work with a specific method on the url
        if(request.getMethod().equals("GET")){
            //Do stuff
        }

        return super.preHandle(request, response, handler);
    } 

    //There is also a postHandle and postCompletion method that can be override     
}

And to register it in WebMvcConfigurerAdapter:

public class SpringMvcContextConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/yourUrl");
    }
}

Another solution could be to use an Aspect with spring-mvc and set a PointCut on the method.

Hope it helped.

Upvotes: 1

Related Questions