Encoding and Servlet API: setContentType or setCharacterEncoding

47,974

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.

Share:
47,974
Sebastien Lorber
Author by

Sebastien Lorber

React expert & early adopter (January 2014) Freelance, working for Facebook/Meta as Docusaurus maintainer since 2020. Author of ThisWeekInReact.com, the best newsletter to stay up-to-date with the React ecosystem:

Updated on February 02, 2020

Comments

  • Sebastien Lorber
    Sebastien Lorber over 4 years

    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?

  • Mr_and_Mrs_D
    Mr_and_Mrs_D over 11 years
    I am missing something : setContentType("text/html"); setCharacterEncoding("UTF-8"); is equivalent to setContentType("text/html; charset=UTF-8"); or just setCharacterEncoding("UTF-8"); will do ?