beautifulday beautifulday - 3 months ago 12
HTTP Question

How to set a header in an HTTP response?

I've a servlet A where I'm setting a header in the HTTP response:

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);
}


Now in a servlet B, I'm trying to get the header value that was set in the servlet A:

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

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




But here the value of userid is coming as
null
. Please let me know what I'm missing here.

Answer

First of all you have to understand the nature of

response.sendRedirect(newUrl);

It is giving the client (browser) 302 http code response with an URL. The browser then makes a separate GET request on that URL. And that request has no knowledge of headers in the first one.

So sendRedirect won't work if you need to pass a header from Servlet A to Servlet B.

If you want this code to work - use RequestDispatcher in Servlet A (instead of sendRedirect). Also, it is always better to use relative path.

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");
}