springboot修改请求头

方法一:

Filter:


 

import org.springframework.util.StringUtils;
 
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
 
/**
* @Description: 滤器实现对请求头的修改
*/
@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("loginId");

        if(!StringUtils.isEmpty(token)){
            headerMapRequestWrapper.addHeader("loginId","456");
        }
        // 放行
        filterChain.doFilter(headerMapRequestWrapper,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}


重写getHeader:

package com.cjh.config;
 
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
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
*/

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;
    }

}


启动类添加注解:@ServletComponentScan

controller:

package com.cjh.controller;



import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/testHeader")
@Slf4j
public class HeardController {


    @Autowired
    private HttpServletRequest httpServletRequest;


    @GetMapping("/testHeader")
    public String testHeader(@RequestHeader String loginId){
        log.info("转换前:{}",loginId);
        log.info("===================");
        String header = httpServletRequest.getHeader("loginId");
        log.info("转换后:{}",header);
        return loginId;
    }
}

通过@RequestHeader注解拿到的请求头还是原来的请求头,需要重新调用httpServletRequest.getHeader() 方法才可以重新拿到修改以后的请求头

方法二:

package com.cjh.config;
 

import org.apache.tomcat.util.http.MimeHeaders;
import org.springframework.util.StringUtils;
 
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
* @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("loginId");

        if(!StringUtils.isEmpty(token)){
            //headerMapRequestWrapper.addHeader("loginId","456");
            Map<String, String> map = new HashMap<>();
            map.put("loginId","456");
            modifyHeaders(map,req);
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }



      private void modifyHeaders(Map<String, String> headerses, HttpServletRequest request){
        if (headerses == null || headerses.isEmpty()) {
            return;
        }
        Class<? extends HttpServletRequest> requestClass = request.getClass();
        try {
            Field request1 = requestClass.getDeclaredField("request");
            request1.setAccessible(true);
            Object o = request1.get(request);
            Field coyoteRequest = o.getClass().getDeclaredField("coyoteRequest");
            coyoteRequest.setAccessible(true);
            Object o1 = coyoteRequest.get(o);
            Field headers = o1.getClass().getDeclaredField("headers");
            headers.setAccessible(true);
            MimeHeaders o2 = (MimeHeaders)headers.get(o1);
            for (Map.Entry<String, String> entry : headerses.entrySet()) {
                o2.removeHeader(entry.getKey());
                o2.addValue(entry.getKey()).setString(entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


@RequestHeader注解拿到的请求头就是已经更改后的请求头。

你可能感兴趣的:(spring,boot,java,spring)