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!