在 Java 中添加自定义 HTTP 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1087140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding custom HTTP headers in java
提问by ravun
I'm trying to create a simulation for our web Portal and need to add custom HTTP headers. I am to assume the user has already been authenticated and these headers are just for storing user information (ie, "test-header: role=user; oem=blahblah; id=123;").
我正在尝试为我们的 Web 门户创建一个模拟,并且需要添加自定义 HTTP 标头。我假设用户已经通过身份验证,这些标头仅用于存储用户信息(即“test-header: role=user; oem=blahblah; id=123;”)。
I've setup a filter to extract the header information but I can't find a way to inject the header information. They don't want it to be stored in cookies and maybe they will want to setup a global filter to include the headers on every page; is it possible to do something like this with the filter interface or through any other methods?
我已经设置了一个过滤器来提取标头信息,但我找不到注入标头信息的方法。他们不希望将其存储在 cookie 中,并且他们可能希望设置一个全局过滤器以在每个页面上包含标题;是否可以使用过滤器接口或任何其他方法来做这样的事情?
采纳答案by rodrigoap
Maybe you can store that information in the session:
也许您可以将该信息存储在会话中:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author rodrigoap
*
*/
public class UserInfoFilter implements Filter {
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest))
throw new ServletException("Can only process HttpServletRequest");
if (!(response instanceof HttpServletResponse))
throw new ServletException("Can only process HttpServletResponse");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.getSession().setAttribute("role", "user");
httpRequest.getSession().setAttribute("id", "123");
filterChain.doFilter(request, response);
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// TODO
}
}
回答by laz
You would need to utilize HttpServletRequestWrapperand provide your custom headers in when the various getHeader* methods are called.
您需要利用HttpServletRequestWrapper并在调用各种 getHeader* 方法时提供自定义标头。

