未在servlet中的请求中插入自定义标头 [英] Custom header not inserted in request in servlet

查看:110
本文介绍了未在servlet中的请求中插入自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个需要通过自定义http标头获取信息的四方派对应用程序,因此我编写了一个简单的测试应用程序来创建此标题,然后重定向到列出所有标题的页面。

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.

生成头的servlet片段是:

The header-generating servlet snippet is:

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

另一方面,header.jsp中的相关代码是:

On the other hand, the relevant code from header.jsp is:

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

显示以下标题:

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 ?

谢谢

推荐答案

重定向你基本上是在指示客户端(webbrowser)发起一个全新的HTTP请求。全新的要求也意味着全新的回应。将其替换为转发

With a redirect you're basically instructing the client (the webbrowser) to fire a brand new HTTP request. A brand new request also means a brand new response. Replace it by a forward:

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

或者如果你真的想在重定向的请求上拥有它,那么创建一个过滤,它映射在 /header.jsp 上并相应地修改标题。

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.

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

另请注意,您正在显示请求 header.jsp 中的标头,而不是响应标头。由于没有直接的API可用于显示响应标头,因此您需要使用外部HTTP标头嗅探工具(如 Firebug Net 面板)或 Fiddler

Also note that you're displaying the request headers in the header.jsp instead of response headers. 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.

这篇关于未在servlet中的请求中插入自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆