Ask a question

Java Spring MVC forward/redirect POST request using interceptor

I have a Spring MVC application which allows users to add/remove favorites via the following calls:

  • POST /api/users/123/favorites/456 (adds item 456 as a favorite for user 123)
  • DELETE /api/users/123/favorites/456 (removes item 456 as a favorite for user 123)

I’d also like to support the following 2 calls that do the exact same thing (assuming user 123 is logged in):

  • POST /api/users/me/favorites/456
  • DELETE /api/users/me/favorites/456

I’ve created an interceptor as shown below:

public class UserMeInterceptor extends HandlerInterceptorAdapter{
    public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception{
        Integer userId = AccessControlUtil.getUserId();
        String redirectUrl = request.getContextPath() + request.getRequestURI().replace( "/me/", "/" + userId + "/" );
        if( redirectUrl.endsWith( "/me" ) ){
            redirectUrl = redirectUrl.replace( "/me", "/" + userId );
        response.sendRedirect( redirectUrl );
        return false;

This approach works great, but only for GET requests. Any way I can forward/redirect a POST request and maintain all POSTed data and method type? Ideally, I want to reuse the same controller that is already defined to handle the case when the ID is passed in.

Article source:

Comments are closed.