Springboot通过过滤器实现对请求头的修改
package com.example.demo.filter; import org.springframework.util.StringUtils; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * @Description: 滤器实现对请求头的修改 * @Author: wanghui */ @WebFilter public class AuthHeaderSettingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; HeaderMapRequestWrapper headerMapRequestWrapper = new HeaderMapRequestWrapper(req); String token = req.getHeader("token"); if(!StringUtils.isEmpty(token)){ headerMapRequestWrapper.addHeader("token",token); } } @Override public void destroy() { Filter.super.destroy(); } }
package com.example.demo.filter; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.util.HashMap; import java.util.Map; /** * @Description: 重写getHeader * @Author: wanghui */ public class HeaderMapRequestWrapper extends HttpServletRequestWrapper { private Map headerMap = new HashMap(); public HeaderMapRequestWrapper(HttpServletRequest request) { super(request); } public void addHeader(String name,String value){ headerMap.put(name,value); } @Override public String getHeader(String name){ String headerValue = super.getHeader(name); String value = (String) this.headerMap.get(name); if(!StringUtils.isEmpty(value)){ return value; } return headerValue; } }