简体   繁体   中英

Server side redirect for REST call

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!

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

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);
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM