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)
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>,否则通常作为泛型类型返回的内容.
小智 9
遇到了这个问题,很惊讶没有人提到RedirectView。我刚刚进行了测试,您可以使用以下方法以干净的100%弹簧方式解决此问题:
@RestController
public class FooController {
@RequestMapping("/foo")
public RedirectView handleFoo() {
return new RedirectView("some-url");
}
}
Run Code Online (Sandbox Code Playgroud)
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)
| 归档时间: |
|
| 查看次数: |
62681 次 |
| 最近记录: |