java - Spring Boot App 注册 RequestContextListener 失败
问题描述
我正在创建简单的 REST 控制器,在我的 Spring Boot 应用程序中,我已经为其添加了配置RequestContextListener
@Configuration
@WebListener
public class DataApiRequestContextListener extends RequestContextListener {
}
在控制器中,我尝试为成功的发布请求构建位置标头
@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();
解决方案
使用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
应该工作并返回您的位置 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);
}
推荐阅读
- lisp - 获取包含三个数字的列表的最大值
- python - 无法操作字符串的内容。例如:检查是否有数字,替换字符和cia
- javascript - 使用 DnD 事件时 Firefox 中的 NoModificationAllowedError
- docker - 为 GKE 上的节点配置最大 pod 数
- 3d-secure - Cardinity Redirect 的 3dsecure 登陆空白页
- javascript - Chrome 自动完成锁定输入,就像它们不可点击一样
- typescript - call() 没有返回正确的类型
- php - 未定义的变量项目 laravel,我试图从数据库中读取数据
- r - R group_by - 如何按 orderID 分组?
- camera-calibration - 如图所示,如何校准完全面向彼此的相机?