gpt4 book ai didi

spring - 如何在spring boot mvc中执行请求之前修改Http headers

转载 作者:行者123 更新时间:2023-12-02 04:29:24 30 4
gpt4 key购买 nike

我有多个休息端点。 userId(http header )在所有端点中都是通用的。我想应用一个逻辑,假设如果未提供则设置其默认值,或者如果在请求进入方法之前在请求中提供则修剪它(例如:心跳)。我们如何在 spring boot rest mvc 中实现这一点。

@RestController
public class MyResource {



@RequestMapping(value = "/heartbeat", method= RequestMethod.GET)
public String heartbeat (@RequestHeader (value="userId", required=false) String userId)
{
...
}
}

最佳答案

你能试试这个吗?

@Configuration
@Slf4j
public class HttpHeaderModificationConfig implements Filter {

private static final String HEADER_DEMO_NAME = "name";

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
// modify HTTP Request Header
final HttpServletRequestWrapper reqWrapper = new HttpServletRequestWrapper(req) {

@Override
public String getHeader(String name) {
if (HEADER_DEMO_NAME.equals(name)) {
return "Changed";
}
return super.getHeader(name);
}
};
log.info("After Changed with Name {}", reqWrapper.getHeader(HEADER_DEMO_NAME));
chain.doFilter(reqWrapper, response);
}

}

关于spring - 如何在spring boot mvc中执行请求之前修改Http headers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543520/

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