简体   繁体   中英

Why is the response body empty when using HttpServletResponse?

Here is my code for a servlet doGet() method:

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

It is properly setting the content type and character encoding, but the response body is empty. What am I doing wrong?

Use this way,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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