Spring MVC和HTML表单的字符编码问题

wwodge7n  于 2022-11-14  发布在  Spring
关注(0)|答案(2)|浏览(144)

我正在使用springmvc,我已经建立了一个web表单,它有两个简单的文本输入,在controller上,我使用@ModelAttribute让spring从web表单构建bean。
The problem comes when user puts on those text fields specials characters, like 酒店 and this kind of stuff, spring doesn't read it as utf-8, and they become the usual bad-encoded string.
我已经检查了web.xml,有utf-8编码过滤器,所有的页面都标记为utf-8,浏览器发送正确的字符集标题。你知道是怎么回事吗?

oyxsuwqo

oyxsuwqo1#

您可能需要查看以下内容:http://forum.springsource.org/showthread.php?81858-ResponseBody-and-UTF-8
简而言之,如果您使用的是带注解的方法,那么使用的messageconverter有一个默认的字符集。您可以通过设置支持的媒体类型在web.xml中更改此设置。
但是,如果您的服务不喜欢该媒体类型,您可能会收到406错误。您可以创建自己的字符串消息转换器并设置默认编码,但使用内置的HttpStringMessageConverter并不容易。
或者,您可以将字串重新编码为不同的字符集:

String newresponse = new String(responseString.getBytes("ISO-8859-1"), "UTF-8");

您也可以在此处查看相关问题:How to get UTF-8 working in Java webapps?

xwbd5t1u

xwbd5t1u2#

解决方案很简单,只需添加products =“text/plain; charset=UTF-8”来请求Map,您可以强制springmvc对返回的文本进行编码。

相关问题