简体   繁体   English

自定义标头未插入servlet的请求中

[英]Custom header not inserted in request in servlet

There's a thrird party app that needs to get information via custom http headers, so I wrote a simple test app that creates this headers and then redirects to a page that lists all headers. 有一个第三方应用程序需要通过自定义的HTTP标头获取信息,因此我编写了一个简单的测试应用程序,该应用程序创建了此标头,然后重定向到列出所有标头的页面。

The header-generating servlet snippet is: 生成标头的servlet片段为:

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 relevant code from header.jsp is: 另一方面,来自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>");
    }
    %>

That 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 the custom header was never inserted. 好像从未插入过自定义标头。 How can I fix it ? 我该如何解决?

Thanks 谢谢

With a redirect you're basically instructing the client (the webbrowser) to fire a brand new HTTP request. 通过重定向,您基本上是在指示客户端(网络浏览器)触发全新的HTTP请求。 A brand new request also means a brand new response. 全新的请求也意味着全新的响应。 Replace it by a forward : 将其替换为转发

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

Or if you actually want to have it on the redirected request, then create a Filter which is mapped on /header.jsp and modifies the header accordingly. 或者,如果您确实希望将其包含在重定向的请求中,则创建一个映射到/header.jspFilter ,并相应地修改标头。

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're displaying the request headers in the header.jsp instead of response headers. 另请注意,您正在header.jsp显示请求标头,而不是响应标头。 Since there's no direct API avaliable to display the response headers, you'd like to investigate them using an external HTTP header sniffing tool like Firebug (the Net panel) or Fiddler . 由于没有可用的直接API显示响应标头,因此您想使用外部HTTP标头嗅探工具(如Firebug网络面板)或Fiddler )来调查它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM