gpt4 book ai didi

java - Spring Boot App 注册 RequestContextListener 失败

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:00 27 4
gpt4 key购买 nike

我正在创建简单的 REST Controller ,为此我在我的 spring boot 应用程序中添加了 RequestContextListener 的配置

@Configuration
@WebListener
public class DataApiRequestContextListener extends RequestContextListener {

}

在 Controller 中,我尝试为成功的发布请求构建位置 header

@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: 没有当前的 ServletRequestAttributes

当我尝试在这一行使用 ServletUriComponentsBuilder 构建位置 URI 时

URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(savedCompany.getId()).toUri();

最佳答案

如果使用 @async 则使用 fromRequestUri

@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);
}

关于java - Spring Boot App 注册 RequestContextListener 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com