Spring Boot App failed to register RequestContextListener… here is a solution to the problem.
Spring Boot App failed to register RequestContextListener
I’m creating a simple REST Controller, and for that I’m adding the configuration of the RequestContextListener
to my spring boot application
@Configuration
@WebListener
public class DataApiRequestContextListener extends RequestContextListener {
}
In the Controller, I tried to build a location header for a successful publish request
@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);
}
I get exceptions
java.lang.IllegalStateException: There is no current ServletRequestAttributes
When I try to build the location URI using ServletUriComponentsBuilder
on this line
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(savedCompany.getId()).toUri();
Solution
If @async
is used, use 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);
}
Or no @async
should work and return your location 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);
}