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?
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 .
getWriter. Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding() .
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 ().
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 .
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 bysetContentType(java.lang.String)
orsetLocale(java.util.Locale)
, this method overrides it. CallingsetContentType(java.lang.String)
with the String oftext/html
and calling this method with the String of UTF-8 is equivalent with callingsetContentType
with the String oftext/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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With