如何在HTTP响应中设置标头?

2022-09-02 22:02:44

我有一个 servlet A,我在 HTTP 响应中设置了一个标头:

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userName=request.getParameter("userName");
    String newUrl = "http://somehost:port/ServletB";

    response.addHeader("REMOTE_USER", userName);

    response.sendRedirect(newUrl);
}

现在在 servlet B 中,我正在尝试获取在 servlet A 中设置的标头值:

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userid = request.getHeader("REMOTE_USER");
}


但是在这里,userid的价值是 .请让我知道我在这里错过了什么。null


答案 1

首先,你必须了解的本质

response.sendRedirect(newUrl);

它给客户端(浏览器)302 http代码响应一个URL。然后,浏览器在该 URL 上发出单独的 GET 请求。并且该请求对第一个请求中的标头一无所知。

因此,如果您需要将标头从 Servlet A 传递到 Servlet B,sendRedirect 将不起作用。

如果您希望此代码正常工作 , 请使用 Servlet A 中的 RequestDispatcher(而不是 sendRedirect)。此外,最好使用相对路径。

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    String userName=request.getParameter("userName");
    String newUrl = "ServletB";
    response.addHeader("REMOTE_USER", userName);
    RequestDispatcher view = request.getRequestDispatcher(newUrl);
    view.forward(request, response);
}

========================

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    String sss = response.getHeader("REMOTE_USER");
}

答案 2

在我的控制器中,我只是添加了一个HttpServletResponse参数并手动添加了标头,不需要过滤器或拦截,并且工作正常:

httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

推荐