我正在使用以下 Package 器来添加标题,它在请求中添加标题
final 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);
}
}
字符串
与过滤器
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
...
mutableRequest.putHeader("x-user-id", "1");
chain.doFilter(mutableRequest, response);
}
型
但我不能在contoller它给空的标题,所以任何人请告诉我如何设置过滤器和访问控制器中的标题。
@GetMapping("/api1/temp1")
private ResponseEntity<Object> temp1(@RequestHeader HttpHeaders headers, @RequestHeader(value="x-user-id",required=false) String userId){
System.out.println(userId));
return new ResponseEntity<Object>("temp1 method", HttpStatus.OK);
}
型
3条答案
按热度按时间lkaoscv71#
当你向控制器发出请求时,第一个OPTIONS请求被发送,在这个请求中过滤器将找不到你设置的值。首先跳过选项请求,然后再试。
字符串
bqjvbblv2#
在MutableHttpServletRequest类中调用getHeaders()以使用@RequestHeader获取值。
字符串
此页面为您提供帮助https://neunggu.tistory.com/50
vfh0ocws3#
您需要重写
HttpServletRequestWrapper#getHeaders(String name)
方法并返回customHeader
值以及其他头值。字符串