Pakira
Pakira

Reputation: 2021

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.

Upvotes: 18

Views: 132686

Answers (3)

hd1
hd1

Reputation: 34657

In my Controller, I merely added an HttpServletResponse parameter and manually added the headers, no filter or intercept required and it works fine:

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

Upvotes: 3

pubsy
pubsy

Reputation: 206

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

Upvotes: 16

mgorniew
mgorniew

Reputation: 11

Header fields are not copied to subsequent requests. You should use either cookie for this (addCookie method) or store "REMOTE_USER" in session (which you can obtain with getSession method).

Upvotes: 0

Related Questions