使用HttpServletResponse时,为什么响应体是空的?

时间:2014-07-08 12:58:45

标签: java http servlets

这是我的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();
}

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

1 个答案:

答案 0 :(得分:0)

使用这种方式,

 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();
     }
}