我正在创建简单的REST控制器,为此我在Spring Boot应用程序中添加了RequestContextListener
@Configuration
@WebListener
public class DataApiRequestContextListener extends RequestContextListener {
}
在控制器中,我尝试ot构建位置标头以成功发布请求
@Async("webExecutor")
@PostMapping("/company")
public CompletableFuture<ResponseEntity<Object>> save(@RequestBody Company company) {
Company savedCompany = companyRepository.save(company);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(savedCompany.getId()).toUri();
ResponseEntity<Object> response = ResponseEntity.created(location).build();
LOGGER.debug("Reponse Status for POST Request is :: " + response.getStatusCodeValue());
LOGGER.debug("Reponse Data for POST Request is :: " + response.getHeaders().getLocation().toString());
return CompletableFuture.completedFuture(response);
}
我得到了例外
java.lang.IllegalStateException: No current ServletRequestAttributes
当我尝试在此行使用ServletUriComponentsBuilder
构建位置URI
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(savedCompany.getId()).toUri();
答案 0 :(得分:2)
如果使用fromRequestUri
则使用@async
@Async("webExecutor")
@PostMapping("/company")
public CompletableFuture<ResponseEntity<Object>> save(HttpServletRequest request, @RequestBody Company company) {
Company savedCompany = companyRepository.save(company);
URI location = ServletUriComponentsBuilder.fromRequestUri(request).path("/{id}")
.buildAndExpand(savedOrganization.getId()).toUri();
ResponseEntity<Object> response = ResponseEntity.created(location).build();
LOGGER.debug("Reponse Status for POST Request is :: " + response.getStatusCodeValue());
LOGGER.debug("Reponse Data for POST Request is :: " + response.getHeaders().getLocation().toString());
return CompletableFuture.completedFuture(response);
}
不带@async
的OR应该可以正常工作,并返回您的位置uri。
@PostMapping("/company")
public CompletableFuture<ResponseEntity<Object>> save(@RequestBody Company company) {
Company savedCompany = companyRepository.save(company);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(savedCompany.getId()).toUri();
ResponseEntity<Object> response = ResponseEntity.created(location).build();
LOGGER.debug("Reponse Status for POST Request is :: " + response.getStatusCodeValue());
LOGGER.debug("Reponse Data for POST Request is :: " + response.getHeaders().getLocation().toString());
return CompletableFuture.completedFuture(response);
}