I want from a servlet to add some plain text content and two headers to the HttpServletResponse

我与影子孤独终老i 提交于 2019-12-13 14:44:39

问题


I want to add some plain text and two headers to the HttpServletResponse, the code is the following:

resp.setContentType("text/plain");

resp.getWriter().write(messages.get(next).getContent());

resp.addHeader("success", "yes");

resp.addHeader("hasnext", ((Boolean)hasNext).toString());

The problem I encounter is that sending the content prevents the sending of the headers. If I don't write the content the headers are received fine, if I include the text they don't.

What is the problem ?


回答1:


Try setting your headers first. Also I'm assuming you call writer.flush() after you are done with your response.

UPDATE

Can you check if the following works:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Content-Type", "text/plain");
    response.setHeader("success", "yes");
    PrintWriter writer = response.getWriter();
    writer.write("hello\n");
    writer.close();
}

Use curl -i http://yourapp.appspot.com to verify the headers.



来源:https://stackoverflow.com/questions/6503308/i-want-from-a-servlet-to-add-some-plain-text-content-and-two-headers-to-the-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!