1、创建Wrapper
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.util.*; /** * [ Filter请求拦截中添加header属性 ] * * @author Love丶TG * @version 1.0.0 * @create 2019 年 11 月 22 日 11:44 */ public 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); } }
2、通过上面这个类,然后简单在Filter中New对象使用即可。
public class RemoteAddrFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
//获得请求参数中的token值
String token = request.getParamter("token");
if(!StringUtils.isEntry(token)){
//如果请求中带有这个参数,则进行过滤加一个header头
requestWrapper.addHeader("tokenr", token);
chain.doFilter(requestWrapper, response); // Goes to default servlet.
}
chain.doFilter(request, response); // Goes to default servlet.
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}