如果我的问题没错,您希望发送的不带
X-API-VERSION标题的请求将自动路由到
headerV2()方法
可以这样做:
从概念上讲,您需要一个在Spring MVC Dispatch
Servlet之前执行的Web筛选器,并且您必须检查该请求是否包含标头,以及是否未添加您认为应该是最新版本的标头(来自配置等)。
这里的一个警告是HttpServletRequest不允许添加标头,因此您必须创建HttpServletRequestWrapper并在其中实现标头添加的逻辑。
这是一个示例借用了实现):
// The web filter import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import java.io.IOException;@Component@Order(1)public class LatestVersionFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; if(req.getHeader("X-API-VERSION")== null) { HeaderMapRequestWrapper wrappedRequest = new HeaderMapRequestWrapper(req); wrappedRequest.addHeader("X-API-VERSION", resolveLastVersion()); filterChain.doFilter(wrappedRequest, servletResponse); } else { filterChain.doFilter(servletRequest, servletResponse); } } private String resolveLastVersion() { // read from configuration or something return "2"; }}
请注意,请求已包装以添加标头,如下所述:
class HeaderMapRequestWrapper extends HttpServletRequestWrapper { public HeaderMapRequestWrapper(HttpServletRequest request) { super(request); } private Map<String, String> headerMap = new HashMap<String, String>(); public void addHeader(String name, String value) { headerMap.put(name, value); } @Override public String getHeader(String name) { String headerValue = super.getHeader(name); if (headerMap.containsKey(name)) { headerValue = headerMap.get(name); } return headerValue; } @Override public Enumeration<String> getHeaderNames() { List<String> names = Collections.list(super.getHeaderNames()); for (String name : headerMap.keySet()) { names.add(name); } return Collections.enumeration(names); } @Override public Enumeration<String> getHeaders(String name) { List<String> values = Collections.list(super.getHeaders(name)); if (headerMap.containsKey(name)) { values.add(headerMap.get(name)); } return Collections.enumeration(values); } }
通过这种实现(确保将servlet放在控制器或其他东西旁边的包中,以便Spring Boot将其识别为组件),您将看到:
- 带有标题的GET
X-API-VERSION=1
将被路由到headerV1()
- 带有标题的GET
X-API-VERSION=2
将被路由到headerV2()
- 没有
X-API-VERSION
标题的GET 将被路由到headerV2()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)