2

I have this line of code:

response.setCharacterEncoding("UTF-8");

I'm getting this error:

The method setCharacterEncoding(String) is undefined for the type HttpServletResponse

Eclipse suggests to cast the response to request which is some thing I don't want to. Can any one help me fix this, please?

zb226
  • 9,586
  • 6
  • 49
  • 79
Lucy
  • 471
  • 4
  • 12
  • 28

3 Answers3

3

See the javadoc. This method exists since servlet 2.4. Either your server supports this version (or later) of the servlet spec, and the jar in your buildpath is too old, or it doesn't support it, and you should not use this method.

In the latter case, read the javadoc to know by what you should replace it.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

Another way would be to set the content type.

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

You can read in the docs on method setContentType:

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.

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
2

The method setCharacterEncoding(String charset) is defined in HttpServletResponse's parent class, ServletResponse. If eclipse complains that it is undefined for the type, you probably have an incorrect import statement. Try deleting all your import statements, and then pressing Ctrl + O.

Jeshurun
  • 22,940
  • 6
  • 79
  • 92