Custom header not inserted into request in servlet

There's a party app there that needs to receive information through custom http headers, so I wrote a simple test application that creates these headers and then redirects to a page listing all the headers.

Servlet snippet generating header:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setHeader("cust-header", "cust-val"); response.sendRedirect("header.jsp"); } 

On the other hand, the corresponding code from header.jsp:

 <% Enumeration enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String string = (String)enumeration.nextElement(); out.println("<font size = 6>" +string +": " + request.getHeader(string)+ "</font><br>"); } %> 

Displays the following headers:

 Host: localhost:9082 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; es-ES; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 (.NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Referer: http://localhost:9082/HdrTest/login.jsp Cookie: JSESSIONID=0000tubMmZOXDyuM4X9RmaYYTg4:-1 

As if a custom header was not inserted. How can i fix this?

thanks

+4
source share
1 answer

With redirection, you basically instruct the client (web browser) to start a new HTTP request. A new request also means a new response. Replace it with forward :

 request.getRequestDispatcher("header.jsp").forward(request, response); 

Or, if you really want to have it in a redirected request, create a Filter that maps to /header.jsp and changes the header accordingly.

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { ((HttpServletResponse) response).setHeader("foo", "bar"); chain.doFilter(request, response); } 

Also note that you display request headers in header.jsp headers instead of response headers. Since there is no direct API that can display response headers, you should examine them using an external tool to nullify the HTTP header, such as Firebug ( Net panel) or Fiddler .

+7
source

All Articles