Java通过过滤器修改header
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/
1、问题所在
项目需要在聚合层做header重写,于是搜集了很多资料,最终确定了使用filter来实现。
2、代码片段
1 package com.filter; 2 3 import org.springframework.stereotype.Component; 4 import org.springframework.web.filter.OncePerRequestFilter; 5 6 import javax.servlet.FilterChain; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletRequestWrapper; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 import java.util.Arrays; 13 import java.util.Collections; 14 import java.util.Enumeration; 15 import java.util.HashMap; 16 import java.util.List; 17 import java.util.Map; 18 19 @Component 20 public class HeadFilter extends OncePerRequestFilter { 21 22 @Override 23 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { 24 HeaderRequestWrapper httpServletRequestWrapper = new HeaderRequestWrapper(request); 25 httpServletRequestWrapper.addHeader("headerTest", "headerTest"); 26 chain.doFilter(httpServletRequestWrapper, response); 27 } 28 29 private class HeaderRequestWrapper extends HttpServletRequestWrapper { 30 31 public HeaderRequestWrapper(HttpServletRequest request) { 32 super(request); 33 } 34 35 private Map<String, String> headerMap = new HashMap<>(); 36 37 public void addHeader(String name, String value) { 38 this.headerMap.put(name, value); 39 } 40 41 @Override 42 public String getHeader(String name) { 43 String headerValue = super.getHeader(name); 44 if (this.headerMap.containsKey(name)) { 45 headerValue = this.headerMap.get(name); 46 } 47 return headerValue; 48 } 49 50 @Override 51 public Enumeration<String> getHeaderNames() { 52 List<String> names = Collections.list(super.getHeaderNames()); 53 for (String name : this.headerMap.keySet()) { 54 names.add(name); 55 } 56 return Collections.enumeration(names); 57 } 58 59 @Override 60 public Enumeration<String> getHeaders(String name) { 61 List<String> values = Collections.list(super.getHeaders(name)); 62 if (this.headerMap.containsKey(name)) { 63 values = Arrays.asList(this.headerMap.get(name)); 64 } 65 return Collections.enumeration(values); 66 } 67 68 } 69 70 }
3、执行效果
4、参考网站
个性签名:1.01的365次方=37.78343433289 >>>1
0.99的365次方= 0.02551796445229 <<<1
每天进步一点点的目标,贵在坚持…