gpt4 book ai didi

java - 如何在 HandlerInterceptorAdapter 中添加 HttpServletRequest header ?

转载 作者:搜寻专家 更新时间:2023-11-01 03:57:11 24 4
gpt4 key购买 nike

我正在尝试将授权 header 添加到我的请求中,作为我们在切换环境时的临时解决方法。我正在尝试在扩展 HandlerInterceptorAdapter 的拦截器中处理它。

我使用了 MutableHttpServletRequest 类 here为了能够将 header 添加到请求中,但似乎没有任何方法可以实际修改拦截器中返回的请求。有什么想法吗?

编辑:或者我必须在过滤器中执行此操作吗?

最佳答案

HttpServletRequest 类型的对象是只读的,为此你应该:

-> 创建一个扩展 HttpServletRequestWrapper 的类(添加一些行为,装饰器模式)

final public class MutableHttpServletRequest extends HttpServletRequestWrapper {

private final Map<String, String> customHeaders;

public MutableHttpServletRequest(HttpServletRequest request){
super(request);
this.customHeaders = new HashMap<String, String>();
}

public void putHeader(String name, String value){
this.customHeaders.put(name, value);
}

public String getHeader(String name) {
String headerValue = customHeaders.get(name);

if (headerValue != null){
return headerValue;
}
return ((HttpServletRequest) getRequest()).getHeader(name);
}

public Enumeration<String> getHeaderNames() {
Set<String> set = new HashSet<String>(customHeaders.keySet());

@SuppressWarnings("unchecked")
Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
while (e.hasMoreElements()) {
String n = e.nextElement();
set.add(n);
}
return Collections.enumeration(set);
}
}

->创建你的过滤器类

public class CustomGatewayFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
mutableRequest.putHeader("referer", "custom value");
chain.doFilter(mutableRequest, response);
}
}

-> 并在您的配置类中添加

 .and().addFilterAfter(new CustomGatewayFilter(), ConcurrentSessionFilter.class)

关于java - 如何在 HandlerInterceptorAdapter 中添加 HttpServletRequest header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40005435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com