Reputation: 1
@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.
@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
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