zoukankan      html  css  js  c++  java
  • 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;
        }
    
    }
    

      

  • 相关阅读:
    C++输入输出缓冲区的刷新问题
    C++11中新特性之:initializer_list详解
    GCC --verbose选项, -lpthread 和-pthread的区别
    C语言的可变参数
    YCM的安装与配置
    【机器学习】正则化的线性回归 —— 岭回归与Lasso回归
    一文读懂线性回归、岭回归和Lasso回归
    美团酒旅数据治理实践
    kettle完成一个数据库到另一个数据的整体迁移
    kettle完成一个数据库到另一个数据的整体迁移
  • 原文地址:https://www.cnblogs.com/wangdahui/p/15103166.html
Copyright © 2011-2022 走看看