java setCharacterEncoding 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10710668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setCharacterEncoding problems
提问by Lucy
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
HttpServletResponse 类型的 setCharacterEncoding(String) 方法未定义
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?
Eclipse 建议将 强制response
转换request
为我不想做的事情。任何人都可以帮我解决这个问题吗?
回答by JB Nizet
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.
请参阅javadoc。这个方法从 servlet 2.4 开始就存在了。要么您的服务器支持此版本(或更高版本)的 servlet 规范,并且您的 buildpath 中的 jar 太旧,要么不支持它,您不应使用此方法。
In the latter case, read the javadoc to know by what you should replace it.
在后一种情况下,请阅读 javadoc 以了解您应该替换它的内容。
回答by Paul Vargas
Another way would be to set the content type.
另一种方法是设置内容类型。
response.setContentType("text/html;charset=UTF-8");
You can read in the docson method setContentType
:
您可以阅读有关方法的文档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.
如果协议提供了这样做的方法,容器必须将用于 servlet 响应的编写器的内容类型和字符编码传达给客户端。在 HTTP 的情况下,使用
Content-Type
标头。
回答by Jeshurun
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.
该方法setCharacterEncoding(String charset)
在HttpServletResponse
的父类中定义ServletResponse
。如果 eclipse 抱怨该类型未定义,则您可能有一个不正确的导入语句。尝试删除所有导入语句,然后按 Ctrl + O。