• HttpServletRequest + Filter 添加 header


    HttpServletRequest + Filter 添加 header

    Filter 能够获得 HttpServletRequest 暴露的接口,但由于 HttpServletRequets 没有 setter方法,因此HttpServletRequest 是只可读的。但很多情况需要往HttpServletRequset 添加 header 参数,例如 tokenuserId

    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。

    参考资料:HttpServletRequest添加header

    自我控制是最强者的本能-萧伯纳
  • 相关阅读:
    蓝书3.6 割点与桥
    蓝书3.5 强连通分量
    蓝书3.4 差分约束系统
    蓝书3.3 SPFA算法的优化
    蓝书3.2 最短路
    蓝书3.1 最小生成树
    luogu 4630 [APIO2018] Duathlon 铁人两项
    Codeforces Round #124 (Div. 1) C. Paint Tree(极角排序)
    dutacm.club Water Problem(矩阵快速幂)
    dutacm.club 1094: 等差区间(RMQ区间最大、最小值,区间GCD)
  • 原文地址:https://www.cnblogs.com/CF1314/p/14689516.html
Copyright © 2020-2023  润新知