Server side redirect for REST call

2019-08-20 20:50发布

问题:

Which is the best way to do a server side redirect for a REST call?

Consider the following scenario:

@RestController
@RequestMapping("/first")
public class FirstController {

    @GetMapping
    public String duStuff(){
        //Redirect to SecondController's doStuff()
    }

}

@RestController
@RequestMapping("/second")
public class SecondController {

    @GetMapping
    public String doStuff(){
        //Redirect here from FirstController's do stuff()
    }

}

I know the HTTP specs state that 3XX response status codes should be used for redirection, but to my understanding that is done on client side (by the client invoking the URI specified by the Location response header).

The only way I've managed to implement this was by using a RestTemplate that does a request from the endpoint in FirstController to the endpoint in SecondController. It works, but I am curious if there is a better way of achieving this.

@RestController
@RequestMapping("/first")
public class FirstController {

    @Autowired
    private RestTemplate template;

    @GetMapping
    public String duStuff(){
        /** Is there a better way of doing this, considering I don't want 
            to get the client involved in the redirect to `second`? */
        return template.getForEntity("second", String.class).getBody();
    }

}

Note: This is not a Spring MVC application (so I can't redirect via return new ModelAndView("redirect:/redirectUrl", model) or RedirectView)

Thanks for your help!

回答1:

Sounds like a design flaw. I would extract what is common between the two @Controllers into a @Service and then invoke the @Service from the @Controllers.



回答2:

For reference: Redirect to an external URL from controller action in Spring MVC

 @RequestMapping(value = "/redirect", method = RequestMethod.GET)
    public void method(HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader("Location", projectUrl);
        httpServletResponse.setStatus(302);
    }


回答3:

If somebody is aware of a good method of achieving this please leave an answer and I will accept it.

There is no out-of-the-box support for a REST server-side redirect.

For a Spring MVC application, you can use ModelAndView("redirect:/redirectUrl", model) or RedirectView.

For REST, you have two options.

  1. Rely on the 3XX status codes and the Location header. This would result in the REST client doing the redirect by invoking the URL from the Location header.
  2. Use a RestTemplate (or another HTTP client) on your server and manually invoke the URL you want to redirect to.


标签: java spring rest