Search code examples
javahttphttp-headershttp-status-code-303

Lost Header during 303 answer


I have the following Handler, who redirects my request to another handler(LoginHandler):

public class ValidationHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange httpExchange) throws IOException
    {
       // Serve for POST requests only
       if (httpExchange.getRequestMethod().equalsIgnoreCase("POST"))
       {  
           Headers hds = httpExchange.getResponseHeaders();
           hds.add("Content-type","text/html");
           hds.add("Location","/login");
           //WHERE I ADD THE USER
           hds.add("User", "someUser");
           //SEND A 303 to go to another handler (LoginHandler)
           httpExchange.sendResponseHeaders(303,0);  
           httpExchange.close();
       }
   }
}

This is the following Header, LoginHeader:

public class LoginHandler implements HttpHandler
{

   @Override
   public void handle(HttpExchange httpExchange) throws IOException
   {
        //I can't read the header USER on the following line!
       httpExchange.getRequestHeaders().forEach((k,v) -> System.out.println(k + ':' + v));

        httpExchange.sendResponseHeaders(200,data.length());
        httpExchange.getResponseBody().write(data.getBytes());
        httpExchange.close();
   }
}

I can't read on the requestHeaders the Header USER that i've added. What am I doing wrong?

Thanks in advance.


Solution

  • Response headers don't follow http redirects. You can either include it as a cookie or as a query parameter to your Location header.

    Change your Location to:

    hds.add("Location","/login?User=someUser");
    

    or add it as a SetCookie header:

    hds.add("Set-Cookie", "User=someuser")
    

    Set-Cookie will tell the browser to store the cookie and include it in all requests back to the server. While including it with your Location will make it accessible one time while handling the redirect.