what is the use of "response.setContentType("text/html")" in servlet

2022-09-02 00:39:09
public class HelloWorld extends HttpServlet{ 
      public void doGet(HttpServletRequest request, 
      HttpServletResponse response)
      throws ServletException,IOException{
      **response.setContentType("text/html");**
      PrintWriter pw = response.getWriter();
      pw.println("<html>");
      pw.println("<head><title>Hello World</title></title>");
      pw.println("<body>");
      pw.println("<h1>Hello World</h1>");
      pw.println("</body></html>");
      }
    }

答案 1

Content types are included in HTTP responses because the same, byte for byte sequence of values in the content could be interpreted in more than one way.(*)

Remember that http can transport more than just HTML (js, css and images are obvious examples), and in some cases, the receiver will not know what type of object it's going to receive.


(*) the obvious one here is XHTML - which is XML. If it's served with a content type of , the receiver ought to just treat it as XML. If it's served up as , then it ought to be treated as XHTML.application/xmlapplication/xhtml+xml


答案 2

From JavaEE docs ServletResponse#setContentType

  • Sets the content type of the response being sent to the client, if the response has not been committed yet.

  • The given content type may include a character encoding specification, for example,

response.setContentType("text/html;charset=UTF-8");

  • The response's character encoding is only set from the given content type if this method is called before is called.getWriter

  • This method may be called repeatedly to change content type and character encoding.

  • This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after has been called or after the response has been committed.getWriter

  • Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.


推荐