xar*_*rqt 2 java spring jvm controller spring-boot
我有一个拦截器,我需要添加代码其他部分所需的自定义标头
public class KeyTaskInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (// a custom condition) {
request. // set custom header key ... `KeyCode`
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
问题是前端不会发送名为“ KeyCode”的自定义标头,并且我无法更改期望此标头的控制器的实现,因此我必须找到一种方法,在发送之前根据 preHandle 方法的请求添加自定义标头向控制器发出请求。有人能帮助我吗?
HttpServletRequest object is read-only and you cannot modify its headers in the HandlerInterceptor. The only thing that you can do with it - is to set attributes and read them later in your controller.
But as in your case you can't change the implementation of the controllers to read attributes, you need actually modify request headers.
There is a way of how to do it - is to use a Filter in which you will substitute the incoming request object with your own request wrapper implementation. By using a request wrapper, you can modify its headers list as you need.
There is a good tutorial that explains how to do it.
Below is an example based on this tutorial, slightly adapted for your use case:
@Component
public class CustomHeaderFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest((HttpServletRequest) request);
mutableRequest.putHeader("KeyCode", "custom value");
chain.doFilter(mutableRequest, response);
}
}
Run Code Online (Sandbox Code Playgroud)
And the implementation of the MutableHttpServletRequest from the tutorial:
class MutableHttpServletRequest extends HttpServletRequestWrapper {
// holds custom header and value mapping
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) {
// check the custom headers first
String headerValue = customHeaders.get(name);
if (headerValue != null){
return headerValue;
}
// else return from into the original wrapped object
return ((HttpServletRequest) getRequest()).getHeader(name);
}
public Enumeration<String> getHeaderNames() {
// create a set of the custom header names
Set<String> set = new HashSet<String>(customHeaders.keySet());
// now add the headers from the wrapped request object
@SuppressWarnings("unchecked")
Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
while (e.hasMoreElements()) {
// add the names of the request headers into the list
String n = e.nextElement();
set.add(n);
}
// create an enumeration from the set and return
return Collections.enumeration(set);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14040 次 |
| 最近记录: |