Spring MVC @RestController和redirect

ale*_*oid 58 rest redirect spring spring-mvc http-redirect

我有一个用Spring MVC @RestController实现的REST端点.有时,取决于我的控制器中的输入参数我需要在客户端上发送http重定向.

有没有可能使用Spring MVC @RestController,如果可以的话,请你举个例子吗?

Nei*_*gan 96

HttpServletResponse参数添加到Handler方法然后调用response.sendRedirect("some-url");

就像是:

@RestController
public class FooController {

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

}
Run Code Online (Sandbox Code Playgroud)

  • 可悲的是,这似乎是唯一的解决方案。我还希望没有HttpServletResponse参数有更好的方法。 (2认同)
  • @MajidLaissi-实际上,这是非常可悲的。在大多数情况下,有可能完全将Spring MVC控制器抽象为完全不依赖HTTP作为传输协议,而这在这里是不可能的。 (2认同)

Arn*_*ter 36

为了避免任何直接依赖,HttpServletRequest或者HttpServletResponse我建议返回一个像这样的ResponseEntity的"纯Spring"实现:

HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
Run Code Online (Sandbox Code Playgroud)

如果您的方法始终返回重定向,请使用ResponseEntity<Void>,否则通常作为泛型类型返回的内容.

  • 或者在一行中返回ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).header(HttpHeaders.LOCATION,newUrl).build();` (7认同)

小智 9

遇到了这个问题,很惊讶没有人提到RedirectView。我刚刚进行了测试,您可以使用以下方法以干净的100%弹簧方式解决此问题:

@RestController
public class FooController {

    @RequestMapping("/foo")
    public RedirectView handleFoo() {
        return new RedirectView("some-url");
    }
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ang 5

redirect表示http代码302,在springMVC中表示Found

这是一个 util 方法,可以将其放置在某种类型中BaseController

protected ResponseEntity found(HttpServletResponse response, String url) throws IOException { // 302, found, redirect,
    response.sendRedirect(url);
    return null;
}
Run Code Online (Sandbox Code Playgroud)

但有时可能想返回 http 代码301,这意味着moved permanently.

在这种情况下,这是 util 方法:

protected ResponseEntity movedPermanently(HttpServletResponse response, String url) { // 301, moved permanently,
    return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).header(HttpHeaders.LOCATION, url).build();
}
Run Code Online (Sandbox Code Playgroud)