How to add and retrieve http headers

Discussions

Web tier: servlets, JSP, Web frameworks: How to add and retrieve http headers

  1. How to add and retrieve http headers (6 messages)

    I am adding one custom header "edmsversion" in my first page, it is visible in it but when the response is redirected to another jsp, my header is lost. In second page, it's not getting. I have copied my code below.
    Please help me.

    My first Page
    -------------------------
    System.out.println("Jsp called successfully");

    response.addHeader("edmsversion","1.2");
    boolean isheader = response.containsHeader("edmsversion");
    System.out.println("contains edmsversion header ..."+isheader);

    response.sendRedirect("/TestHeaderResponse.jsp");

    TestHeaderResponse.jsp
    ----------------------------------
    System.out.println("Test header response page called successfully");

    String stringversion = request.getHeader("edmsversion");
    System.out.println("edms version header : "+stringversion);

    Enumeration headernames = request.getHeaderNames();
    System.out.println("Headers---------");
    while (headernames.hasMoreElements()){
    String headername = (String)headernames.nextElement();
    String headervalue = request.getHeader(headername);
    System.out.println(headername+"----"+headervalue);
    }

  2. I believe if you "forward" rather than redirecting then your header information should be ok. As far as I am aware the response is considered "committed" (if you sendRedirect) and cannot be used, in terms of supplying information from one page to the next.

    Try using RequestDespatcher.forward or PageContext.forward or the jsp forward tag (depending upon your need) - they all result in the request, response being supplied to the next page/servlet.

    Hope that helps.

    Mark Buchner

    n.b. be sure to makes changes to the header (incl. cookies, etc) *before* you perform the forward operation - goes without saying really.
  3. Hi Mark Buchner,

    Thanks for the response.
    I have already tried RequestDispacher and jsp:forward. It is not working. Is there any other way of calling another jsp/ servlet so that the header info can be retrieved.

    Is there any pre-requiste/ constraint for adding header??

    Preeti
  4. In this situation, you may be better off using the HttpSession object. We had to write code that manipulated the header variables, and it got pretty complicated. We ended up having to intercept the request, and manually append headers, and then forward the request.
  5. Hi Steve Albee,

    My need is to add the http header only. I cann't do it using session object. Do you have any other idea??
  6. Hi Steve Albe,

    Can you please send me the code in which you have manually appended the headers??

    Thanks
  7. Hi Preeti,

    The code I refered to is available in "Java Examples in a Nutshell" from O'Reilly. Take a look at the Server and ProxyServer classes.