Java 使用Spring Webflux的HTTP 201的绝对位置头
我有一个反应式REST控制器(带有SpringWebFlux),在执行POST请求时,我想设置一个到资源的绝对链接,该资源刚刚创建到必选的Java 使用Spring Webflux的HTTP 201的绝对位置头,java,spring-webflux,Java,Spring Webflux,我有一个反应式REST控制器(带有SpringWebFlux),在执行POST请求时,我想设置一个到资源的绝对链接,该资源刚刚创建到必选的位置头中。到目前为止,我只能创建相对链接。添加org.springframework.http.server.reactive.ServerHttpRequest或org.springframework.web.server.ServerWebExchange作为额外的方法参数,以检索主机信息等。导致http 415响应,而未到达控制器方法 @RequestM
位置头中。到目前为止,我只能创建相对链接。添加org.springframework.http.server.reactive.ServerHttpRequest
或org.springframework.web.server.ServerWebExchange
作为额外的方法参数,以检索主机信息等。导致http 415响应,而未到达控制器方法
@RequestMapping("/v1/stuffs")
@RestController
public class StuffController {
@PostMapping
public Mono<ResponseEntity<Stuff>> createStuff(
@Valid @NotNull @RequestBody Mono<Stuff> stuff) {
UUID id = UUID.randomUUID();
URI uri = UriComponentsBuilder.newInstance().pathSegment("v1", "stuffs", id.toString()).build().toUri();
// ugly approach with help of spring-hateoas, which resulted in a relative link too
// URI uri = WebFluxLinkBuilder.linkTo(WebFluxLinkBuilder.methodOn(StuffController.class).getStuff(id)).withSelfRel().toMono().block().toUri();
return stuff
.map(it -> stuffService.create(id, it))
.map(it -> ResponseEntity.created(uri).build());
}
@GetMapping("/{id}")
public Mono<ResponseEntity<Stuff>> getStuff(@NotNull @PathVariable("id") UUID id) {
// ...
}
}
@RequestMapping(“/v1/stuffs”)
@RestController
公共类填充控制器{
@邮戳
公共物品(
@有效的@NotNull@RequestBody(数据){
UUID id=UUID.randomuid();
URI URI=UriComponentsBuilder.newInstance().pathSegment(“v1”,“stuff”,id.toString()).build().tori();
//在spring hateoas的帮助下采用了丑陋的方法,这也导致了一个相对的联系
//URI URI=WebFluxLinkBuilder.linkTo(WebFluxLinkBuilder.methodOn(StuffController.class).getStuff(id)).Wiselfrel().toMono().block().Tori();
退货
.map(it->stuffService.create(id,it))
.map(it->ResponseEntity.created(uri.build());
}
@GetMapping(“/{id}”)
公共Mono getStuff(@NotNull@PathVariable(“id”)UUID id){
// ...
}
}
向控制器的方法签名添加UriComponentsBuilder componentsBuilder
,应能使其正常工作:
@PostMapping
public Mono<ResponseEntity<Stuff>> createStuff(
@Valid @NotNull @RequestBody Mono<Stuff> stuff,
UriComponentsBuilder componentsBuilder) {
...
URI uri = componentsBuilder.path("/v1/stuffs/{id}").buildAndExpand(id.toString()).toUri();
...
}
@PostMapping
公共物品(
@有效@NotNull@RequestBody,
UriComponentsBuilder(组件生成器){
...
uriuri=componentsBuilder.path(“/v1/stuffs/{id}”).buildAndExpand(id.toString()).tori();
...
}