在java中添加自定义HTTP标头

时间:2009-07-06 14:00:40

标签: java http header

我正在尝试为我们的门户网站创建模拟,并需要添加自定义HTTP标头。我假设用户已经过身份验证,这些标题只是用于存储用户信息(即“test-header:role = user; oem = blahblah; id = 123;”)。

我已经设置了一个过滤器来提取标题信息,但我找不到一种方法来注入标题信息。他们不希望将它存储在cookie中,也许他们想要设置一个全局过滤器来在每个页面上包含标题;是可以使用过滤器界面或通过任何其他方法做这样的事情吗?

3 个答案:

答案 0 :(得分:1)

也许您可以在会话中存储该信息:


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
    }

}

答案 1 :(得分:0)

您可以使用addHeader

答案 2 :(得分:0)

在调用各种getHeader *方法时,您需要使用HttpServletRequestWrapper并提供自定义标头。