首页 > 解决方案 > 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();

标签: javaspringspring-bootspring-web

解决方案


使用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);
}

推荐阅读