HttpServletRequest + Filter 添加 header
Filter 能够获得 HttpServletRequest 暴露的接口,但由于 HttpServletRequets 没有 setter方法,因此HttpServletRequest 是只可读的。但很多情况需要往HttpServletRequset 添加 header 参数,例如 token、userId。
1、自定义配置类
配置类继承 HttpServletRequestWrapper
public class CustomHttpServletRequest extends HttpServletRequestWrapper {
private final Map<String, String> hashMap;
/**
* 初始化
*
* @param request
*/
public CustomHttpServletRequest(HttpServletRequest request) {
super(request);
hashMap = new HashMap<>();
}
/**
* 添加key、value
*
* @param key
* @param value
*/
public void addHeader(String key, String value) {
hashMap.put(key, value);
}
/**
* 获得value
*
* @param key
* @return
*/
@Override
public String getHeader(String key) {
String value = super.getHeader(key);
if (value == null) {
value = hashMap.get(key);
}
return value;
}
/**
* 获得value集合
*
* @param key
* @return
*/
@Override
public Enumeration<String> getHeaders(String key) {
Enumeration<String> enumeration = super.getHeaders(key);
List<String> valueList = Collections.list(enumeration);
if (hashMap.containsKey(key)) {
valueList.add(hashMap.get(key));
}
return Collections.enumeration(valueList);
}
/**
* 获得key集合
*
* @return
*/
@Override
public Enumeration<String> getHeaderNames(){
List<String> keyList = Collections.list(super.getHeaderNames());
keyList.addAll(hashMap.keySet());
return Collections.enumeration(keyList);
}
}
2、Filter
Filter 调用配置类对象并添加 header
@WebFilter(filterName = "AccessFilter", urlPatterns = "/*")
@Order(1)
public class AccessFilter implements Filter {
Logger logger = LoggerFactory.getLogger(AccessFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
CustomHttpServletRequest customHttpServletRequest = new CustomHttpServletRequest(request);
//添加header
customHttpServletRequest.addHeader("test", "123");
filterChain.doFilter(customHttpServletRequest, servletResponse);
}
@Override
public void destroy() {
}
启动类添加 ServletComponentScan
注解
@MapperScan({"com.lin.mapper"})
@SpringBootApplication
@EnableTransactionManagement
@ServletComponentScan
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
3、测试
调用接口进行测试
@GetMapping(value = "/findById")
@ResponseBody
public Result findById(@RequestParam(value = "id", required = true, defaultValue = "2") Long id,
HttpServletRequest request) {
User user = userService.findById(id);
logger.info("===========" + request.getHeader("test") + "==========");
return ResultUtil.success(user);
}
打印出结果:
INFO 13880 --- [nio-8080-exec-2] com.lin.controller.UserController : ===========123==========
总结:自定义配置类继承 HttpServletRequestWrapper,Filter 调用配置类并添加 header, 接口通过 getheader 方法获得已添加的 header。