Spring MVC @RestController and redirect

2019-01-22 05:56发布

I have a REST endpoint implemented with Spring MVC @RestController. Sometime, depends on input parameters in my controller I need to send http redirect on client.

Is it possible with Spring MVC @RestController and if so, could you please show an example ?

3条回答
smile是对你的礼貌
2楼-- · 2019-01-22 05:59

Add an HttpServletResponse parameter to your Handler Method then call response.sendRedirect("some-url");

Something like:

@RestController
public class FooController {

  @RequestMapping("/foo")
  void handleFoo(HttpServletResponse response) throws IOException {
    response.sendRedirect("some-url");
  }

}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-22 06:02

To avoid any direct dependency on HttpServletRequest or HttpServletResponse I suggest a "pure Spring" implementation returning a ResponseEntity like this:

HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);

If your method always returns a redirect, use ResponseEntity<Void>, otherwise whatever is returned normally as generic type.

查看更多
Root(大扎)
4楼-- · 2019-01-22 06:07

if you @RestController returns an String you can use something like this

return "redirect:/other/controller/";

and this kind of redirect is only for GET request, if you want to use other type of request use HttpServletResponse

登录 后发表回答