gpt4 book ai didi

java - Servlet 过滤器 : How to get all the headers from servletRequest?

转载 作者:IT老高 更新时间:2023-10-28 20:47:29 25 4
gpt4 key购买 nike

这是我的 WebFilter 的样子

@WebFilter("/rest/*")
public class AuthTokenValidatorFilter implements Filter {

@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
final Enumeration<String> attributeNames = servletRequest.getAttributeNames();
while (attributeNames.hasMoreElements()) {
System.out.println("{attribute} " + servletRequest.getParameter(attributeNames.nextElement()));
}

final Enumeration<String> parameterNames = servletRequest.getParameterNames();
while (parameterNames.hasMoreElements()) {
System.out.println("{parameter} " + servletRequest.getParameter(parameterNames.nextElement()));
}
filterChain.doFilter(servletRequest, servletResponse);
}

@Override
public void destroy() {
}
}

我试图在网上了解如何从请求中获取 HTTP header 的值。

我没有找到任何东西,所以我尝试在不知道任何东西的情况下枚举 servletRequest.getAttributeNames()servletRequest.getParameterNames(),但我没有得到任何标题。

问题
如何获取请求中的所有 header ?

最佳答案

Typecast ServletRequestHttpServletRequest (仅当 ServletRequest requestinstanceof HttpServletRequest)。

然后就可以使用HttpServletRequest.getHeader()HttpServletRequest.getHeaderNames()方法了。

类似这样的:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
Enumeration<String> headerNames = httpRequest.getHeaderNames();

if (headerNames != null) {
while (headerNames.hasMoreElements()) {
System.out.println("Header: " + httpRequest.getHeader(headerNames.nextElement()));
}
}

//doFilter
chain.doFilter(httpRequest, response);
}

关于java - Servlet 过滤器 : How to get all the headers from servletRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25247218/

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