在我们切换环境时,我尝试在我的请求中添加一个Authorization标头作为临时解决方法。我试图在一个扩展HandlerInterceptorAdapter的拦截器中处理它。
我使用了MutableHttpServletRequest类here以便能够将标头添加到请求中,但它似乎没有任何方法可以在拦截器中实际修改返回的请求。有什么想法吗?
编辑:或者我必须在过滤器中执行此操作吗?
答案 0 :(得分:0)
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)
答案 1 :(得分:-3)
{{1}}