Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding and Servlet API: setContentType or setCharacterEncoding

Just wonder what is behind the scene. Actually it seems that we can set the encoding with:

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

What is the difference?

like image 596
Sebastien Lorber Avatar asked Feb 01 '11 16:02

Sebastien Lorber


People also ask

What is the use of setContentType in Servlet?

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, text/html;charset=UTF-8 .

What is the purpose of the getWriter () method of ServletResponse?

getWriter. Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding() .

What is Servlet response?

A ServletResponse object is created by the servlet container and passed as an argument to the servlet's service function. Use the ServletOutputStream supplied by getOutputStream to deliver binary data in a MIME body response (). Use the PrintWriter object given by getWriter to deliver character data ().

What is ServletRequest?

A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest .


1 Answers

The javadoc is pretty clear about the difference:

void setCharacterEncoding(String charset) Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8. If the character encoding has already been set by setContentType(java.lang.String) or setLocale(java.util.Locale), this method overrides it. Calling setContentType(java.lang.String) with the String of text/html and calling this method with the String of UTF-8 is equivalent with calling setContentType with the String of text/html; charset=UTF-8.


void setContentType(String type) 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, text/html;charset=UTF-8.

like image 89
skaffman Avatar answered Sep 21 '22 17:09

skaffman