Spring MVC中的UTF-8编码问题
我有一个 Spring MVC bean,我想通过设置编码 UTF-8 返回土耳其字符。但虽然我的字符串是“şŞğĞіıçÇöÖüÜ”,但它返回为“??????çÇöÖüÜ”。而且当我查看响应页面(即 Internet Explorer 页面)时,编码是西欧 ISO,而不是 UTF-8。
这是代码:
@RequestMapping(method=RequestMethod.GET,value="/GetMyList")
public @ResponseBody String getMyList(HttpServletRequest request, HttpServletResponse response) throws CryptoException{
String contentType= "text/html;charset=UTF-8";
response.setContentType(contentType);
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setCharacterEncoding("utf-8");
String str="şŞğĞİıçÇöÖüÜ";
return str;
}
I' ve a Spring MVC bean and I would like to return turkish character by setting encoding UTF-8. but although my string is "şŞğĞİıçÇöÖüÜ" it returns as "??????çÇöÖüÜ". and also when I look at the response page, which is internet explorer page, encoding is western european iso, not UTF-8.
Here is the code:
@RequestMapping(method=RequestMethod.GET,value="/GetMyList")
public @ResponseBody String getMyList(HttpServletRequest request, HttpServletResponse response) throws CryptoException{
String contentType= "text/html;charset=UTF-8";
response.setContentType(contentType);
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setCharacterEncoding("utf-8");
String str="şŞğĞİıçÇöÖüÜ";
return str;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
我已经弄清楚了,您可以添加到请求映射 Produce = "text/plain;charset=UTF-8"
请参阅此博文以了解有关解决方案的更多详细信息
I've figured it out, you can add to request mapping produces = "text/plain;charset=UTF-8"
see this blog post for more details on the solution
在您的调度程序 servlet 上下文 xml 中,您必须添加一个属性
viewResolver bean 上的
""
。我们正在使用 freemarker 来获取视图。
它看起来像这样:
in your dispatcher servlet context xml, you have to add a propertie
"<property name="contentType" value="text/html;charset=UTF-8" />"
on your viewResolver bean.we are using freemarker for views.
it looks something like this:
自行将 JSON 字符串转换为 UTF-8。
Convert the JSON string to UTF-8 on your own.
在 Spring 5 或早期版本中,有
MediaType
类。它已经有正确的行,如果你想遵循 DRY:所以我使用这套与控制器相关的注释:
它在文档中被标记为已弃用,但我遇到了这个问题,它比复制粘贴上述内容更好我认为,在整个应用程序的每个方法/控制器上都行。
In Spring 5, or maybe in earlier versions, there is
MediaType
class. It has already correct line, if you want to follow DRY:So I use this set of controller-related annotations:
It is marked deprecated in the docs, but I've run into this issue and it is better than copy-pastying the aforementioned line on every method/controller throughout your application, I think.
您需要在
RequestMapping
注释中添加字符集:You need add charset in the
RequestMapping
annotation:我发现“@RequestMapping Produces =”和其他配置更改对我没有帮助。当您执行 resp.getWriter() 时,在编写器上设置编码也为时已晚。
向 HttpServletResponse 添加标头是可行的。
I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.
Adding a header to the HttpServletResponse works.
还有一些类似的问题:Spring MVC响应编码问题,使用 @ResponseBody 自定义 HttpMessageConverter 来执行 Json 操作。
然而,我的简单解决方案:
并且视图 html_utf8.jsp
没有额外的类和配置。
您还可以为其他内容类型创建另一个视图(例如 json_utf8)。
There are some similar questions: Spring MVC response encoding issue, Custom HttpMessageConverter with @ResponseBody to do Json things.
However, my simple solution:
and the view html_utf8.jsp
No additional classes and configuration.
And You can also create another view (for example json_utf8) for other content type.
我通过将生成的返回类型推断到第一个 GET requestMethod 中解决了这个问题。这里重要的部分是
所以每一个如何使用/account/**,Spring都会返回application/json;charset=UTF-8内容类型。
因此,您不必为控制器中的每个方法进行设置,您可以为整个类进行设置。如果您需要对特定方法进行更多控制,则只需推断生成的返回内容类型即可。
I've resolved this issue by inferring the produced return type into the first GET requestMethod. The important part here is the
So every one how use /account/**, Spring will return application/json;charset=UTF-8 content type.
So, you do not have to set up for each method in your Controller, you can do it for the entire class. If you need more control over a specific method, you just only have to infer the produces return content type.
还要添加到您的 bean 中:
对于 @ExceptionHandler :
如果您使用
它应该在 beans 之后。Also add to your beans :
For @ExceptionHandler :
If you use
<mvc:annotation-driven/>
it should be after beans.如果您使用的是 Spring MVC 版本 5,您还可以使用
@GetMapping
注释来设置编码。下面是一个将内容类型设置为 JSON 并将编码类型设置为 UTF-8 的示例:有关 @GetMapping 注释的更多信息,请参见:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/ org/springframework/web/bind/annotation/GetMapping.html
If you are using Spring MVC version 5 you can set the encoding also using the
@GetMapping
annotation. Here is an example which sets the content type to JSON and also the encoding type to UTF-8:More information on the @GetMapping annotation here:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html
当您尝试发送特殊字符(如 è、à、ù 等)时,您可能会在 Jsp Post 页面中看到许多字符,如“£”、“Ä”或“Æ”。
要在 99% 的情况下解决此问题,您可以在 web.xml 中将这段代码移至文件头部:
有关完整示例,请参见此处:https://lentux-informatica.com/spring-mvc-utf-8-encoding-problem-solved/
When you try to send special characters like è,à,ù, etc etc, may be you see in your Jsp Post page many characters like '£','Ä’ or ‘Æ’.
To solve this problem in 99% of cases you may move in your web.xml this piece of code at the head of file:
For complete example see here : https://lentux-informatica.com/spring-mvc-utf-8-encoding-problem-solved/
如果使用 Spring Boot,只需将此属性添加到您的 applications.properties 文件中:
If are using spring boot just add this properies to your applications.properties file:
如果您使用 Spring Boot(使用 3.0.4 进行测试),则默认情况下 UTF-8 对于 HTTP POST 请求和响应都将开箱即用。
如果您手动添加了 Spring MVC,那么您需要配置两件事:
Content-Type
HTTP 标头字段。如果没有这个,Content-Type
标头通常会是text/html;charset=ISO-8859-1
而不是 UTF-8。如何设置CharacterEncodingFilter?
这取决于您的网络应用程序配置。您应该研究一下如何设置 Servlet 过滤器。对于
CharacterEncodingFilter
,您需要将encoding
参数设置为utf-8
,将forceEncoding
设置为正确。
例如,如果您使用
web.xml
来配置 Servlet 过滤器,那么您可以在web.xml
中使用类似的内容:如果这不起作用(意味着,您的 MVC 控制器不会接收 UTF-8 格式的请求参数),那么您需要将
characterEncodingFilter
移至web.xml
中的更高位置,以便在之前调用它其他过滤器。如何设置StringHttpMessageConverter?
更改/添加您的
WebMvcConfigurer
如下:它默认使用
StandardCharsets.ISO_8859_1
,但上面的代码会将其更改为 UTF-8。您可以通过检查 HTTP 响应中的Content-Type
标头来验证这是否有效。现在应该显示text/html;charset=UTF-8
而不是text/html;charset=ISO-8859-1
。If you are using Spring Boot (tested with 3.0.4), then UTF-8 will work out of the box by default for both HTTP POST requests and responses.
If you have manually added Spring MVC, then you'll need to configure two things:
Content-Type
HTTP header field. Without this, theContent-Type
header will usually betext/html;charset=ISO-8859-1
instead of UTF-8.How to set CharacterEncodingFilter?
It depends on your web app configuration. You should look into how you can set a Servlet Filter in general. For
CharacterEncodingFilter
you'll need to set theencoding
param toutf-8
and theforceEncoding
totrue
.For example, if you are using
web.xml
to configure Servlet Filters, then you could use something like this in yourweb.xml
:If this doesn't work (meaning, your MVC controller doesn't receive request parameters as UTF-8), then you need to move the
characterEncodingFilter
higher up inweb.xml
, so that it gets called before other filters.How to set StringHttpMessageConverter?
Change/add your
WebMvcConfigurer
to something like this:It uses
StandardCharsets.ISO_8859_1
by default, but the code above will change it to UTF-8. You can verify if this is working, by checking theContent-Type
header in the HTTP responses. Which should now showtext/html;charset=UTF-8
instead oftext/html;charset=ISO-8859-1
.