【问题标题】:Why is the response body empty when using HttpServletResponse?为什么使用 HttpServletResponse 时响应体为空?
【发布时间】:2014-07-08 12:58:44
【问题描述】:

这是我的 servlet doGet() 方法代码:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String admin = "true";
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter writer = resp.getWriter();
    writer.write(admin);
    writer.flush();
}

正确设置内容类型和字符编码,但响应正文为空。我做错了什么?

【问题讨论】:

  • 检查是否有exception
  • resp.setContentType("text/html;charset=UTF-8");
  • 它对我来说很好用,这让我觉得这不是你的实际代码,而是一些过于简化的版本。你如何使用你的代码?是否有一些重定向?
  • 这是实际代码。我曾经尝试调试,并且在此过程中以某种方式在响应正文中看到了预期的输出,但我无法复制它。
  • 也适合我。你用的是什么http客户端?您如何查找响应内容?

标签: java http servlets


【解决方案1】:

这样用,

 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    String admin = "true";

     resp.setContentType("text/plain; charset=utf-8");
     resp.setCharacterEncoding("UTF-8");

     PrintWriter out = resp.getWriter();
     try {

        out.println(admin);
     } finally {            
        out.close();
     }
}

【讨论】:

  • 这会发生什么变化?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 2013-11-09
  • 1970-01-01
  • 2020-06-15
  • 2012-09-26
相关资源
最近更新 更多