Я пытаюсь добавить местоположение в заголовок ответа для конкретного API. Однако я не вижу параметр местоположения в заголовке ответа, когда отправляю запрос к связанному API через Postman. Почтальон показывает только тип контента, кодировку передачи, дату, подтверждение активности и параметры подключения, но внутри заголовков нет местоположения.
Я использую открытый API генерируется код и классы интерфейса API. Я переопределяю методы этих классов интерфейса в классах контроллеров, поэтому не могу изменить сигнатуры методов. Я делюсь методом контроллера и фильтром сервлетов, которые я пытаюсь отправить в заголовках внутри. Как я могу увидеть параметр местоположения внутри заголовков ответов? :
Метод контроллера:
@ResponseStatus(HttpStatus.CREATED) // Sets 201 Created status
public FlightInfo addFlight(final FlightInfo request) {
// Call the service to add the flight
final FlightInfo savedFlight = flightService.addFlight(request);
// Set the flight ID as a request attribute for the filter to use
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest httpRequest = attr.getRequest();
httpRequest.setAttribute("flightId", savedFlight.getFlightId());
// Return the FlightInfo response
return savedFlight;
}
Фильтр сервлетов:
import java.io.IOException;
import java.net.URI;
import java.util.UUID;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@Component
public class FlightFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// Proceed with the filter chain to allow the controller to process the request
chain.doFilter(request, response);
// After the controller has processed the request, check if it’s a POST request to /flight
if (request.getRequestURI().contains("/flight") && request.getMethod().equalsIgnoreCase("POST")) {
// Retrieve the flight ID from a request attribute
UUID flightId = (UUID) request.getAttribute("flightId");
if (flightId != null) {
// Build the Location URI for the newly created flight
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(flightId)
.toUri();
// Add the Location header to the response
response.setHeader("Location", location.toString());
System.out.println("Location header set: " + location.toString());
} else {
System.out.println("Flight ID is null");
}
} else {
System.out.println("Request URI: " + request.getRequestURI() + ", Method: " + request.getMethod());
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... er-in-java