我尝试在特定 API 的响应标头中添加一个位置。但是,当我通过Postman向相关API发送请求时,我在响应标头中看不到位置参数。 Postman 仅显示
content-type
、传输编码、日期、保持活动和连接参数,但标头内没有位置。
我使用开放的API代码生成并生成API的接口类。我在控制器类中重写了这些接口类中的方法,因此无法更改方法签名。我正在共享控制器方法和 servlet 过滤器,我尝试在
headers
中发送位置。如何查看响应标头中的位置参数? :
控制器方法:
@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;
}
Servlet 过滤器:
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());
}
}
您确定您的文件管理器已被调用吗?您在过滤器的日志中看到任何输出吗? (顺便说一句,我建议使用记录器而不是
System.out.println
)。我认为您缺少注释@Order
,并且可能是您的过滤器未使用。另外,由于您只想将过滤器应用于路径“/flight/*”,因此有一种更好的方法可以使用 FilterRegistrationBean
注册过滤器。请参阅此处有关该主题的好文章:How to Define a Spring Boot Filter?