1、问题所在
项目需要在聚合层做header重写,于是搜集了很多资料,最终确定了使用filter来实现。
- 代码片段
package com.filter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class HeadFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
HeaderRequestWrapper httpServletRequestWrapper = new HeaderRequestWrapper(request);
httpServletRequestWrapper.addHeader("headerTest", "headerTest");
chain.doFilter(httpServletRequestWrapper, response);
}
private class HeaderRequestWrapper extends HttpServletRequestWrapper {
public HeaderRequestWrapper(HttpServletRequest request) {
super(request);
}
private Map<String, String> headerMap = new HashMap<>();
public void addHeader(String name, String value) {
this.headerMap.put(name, value);
}
@Override
public String getHeader(String name) {
String headerValue = super.getHeader(name);
if (this.headerMap.containsKey(name)) {
headerValue = this.headerMap.get(name);
}
return headerValue;
}
@Override
public Enumeration<String> getHeaderNames() {
List<String> names = Collections.list(super.getHeaderNames());
for (String name : this.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 (this.headerMap.containsKey(name)) {
values = Arrays.asList(this.headerMap.get(name));
}
return Collections.enumeration(values);
}
}
}