如何解决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;
}
解决方法
我已经弄清楚了,您可以添加到请求映射中,产生= \“ text / plain; charset = UTF-8 \”
@RequestMapping(value = \"/rest/create/document\",produces = \"text/plain;charset=UTF-8\")
@ResponseBody
public void create(Document document,HttpServletRespone respone) throws UnsupportedEncodingException {
Document newDocument = DocumentService.create(Document);
return jsonSerializer.serialize(newDocument);
}
有关解决方案的更多详细信息,请参见此博客文章。
,在调度程序servlet上下文xml中,您必须添加一个属性
在viewResolver bean上2ѭ。
我们正在使用freemarker进行查看。
它看起来像这样:
<bean id=\"viewResolver\" class=\"org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver\">
...
<property name=\"contentType\" value=\"text/html;charset=UTF-8\" />
...
</bean>
,自行将JSON字符串转换为UTF-8。
@RequestMapping(value = \"/example.json\",method = RequestMethod.GET)
@ResponseBody
public byte[] example() throws Exception {
return \"{ \'text\': \'äöüß\' } \".getBytes(\"UTF-8\");
}
,还有一些类似的问题:Spring MVC响应编码问题,使用@ResponseBody自定义HttpMessageConverter来执行Json事情。
但是,我的简单解决方案是:
@RequestMapping(method=RequestMethod.GET,value=\"/GetMyList\")
public ModelAndView getMyList(){
String test = \"čćžđš\";
...
ModelAndView mav = new ModelAndView(\"html_utf8\");
mav.addObject(\"responseBody\",test);
}
和视图html_utf8.jsp
<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>${responseBody}
没有其他的类和配置。
您还可以为其他内容类型创建另一个视图(例如json_utf8)。
,还要添加到您的bean中:
<bean class=\"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter\">
<property name=\"messageConverters\">
<array>
<bean class=\"org.springframework.http.converter.StringHttpMessageConverter\">
<constructor-arg index=\"0\" name=\"defaultCharset\" value=\"UTF-8\"/>
<property name=\"supportedMediaTypes\">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean></bean>
对于@ExceptionHandler:
enter code<bean class=\"org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver\">
<property name=\"messageConverters\">
<array>
<bean class=\"org.springframework.http.converter.StringHttpMessageConverter\">
<constructor-arg index=\"0\" name=\"defaultCharset\" value=\"UTF-8\"/>
<property name=\"supportedMediaTypes\">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class=\"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter\">
<property name=\"supportedMediaTypes\">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>
</array>
</property>
</bean>
如果您使用<mvc:annotation-driven/>
,则应放在豆角后面。
,我通过将产生的返回类型推断到第一个GET requestMethod中解决了此问题。这里重要的是
produces=\"application/json;charset=UTF-8
因此,每一个如何使用/ account / **,Spring都会返回application / json; charset = UTF-8内容类型。
@Controller
@Scope(\"session\")
@RequestMapping(value={\"/account\"},method = RequestMethod.GET,produces=\"application/json;charset=UTF-8\")
public class AccountController {
protected final Log logger = LogFactory.getLog(getClass());
....//More parameters and method here...
@RequestMapping(value={\"/getLast\"},method = RequestMethod.GET)
public @ResponseBody String getUltimo(HttpServletResponse response) throws JsonGenerationException,JsonMappingException,IOException{
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
Account account = accountDao.getLast();
return writer.writeValueAsString(account);
}
catch (Exception e) {
return errorHandler(e,response,writer);
}
}
因此,您不必为Controller中的每个方法进行设置,而可以为整个类进行设置。如果您需要对特定方法进行更多控制,则只需推断Produces返回内容类型。
,当您尝试发送诸如è,à,ù等特殊字符时,您可能会在Jsp Post页面上看到许多字符,例如\'£\',\'Ä'或'Æ'。
为了在99%的情况下解决此问题,您可以在web.xml中将以下代码移至文件的开头:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
有关完整的示例,请参见此处:https://lentux-informatica.com/spring-mvc-utf-8-encoding-problem-solved/
,如果您使用的是Spring MVC版本5,则还可以使用@GetMapping
注释设置编码。这是一个将内容类型设置为JSON并将编码类型设置为UTF-8的示例:
@GetMapping(value=\"/rest/events\",produces = \"application/json; charset=UTF-8\")
有关@GetMapping批注的更多信息,请参见:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html
,在Spring 5中,或者也许在较早的版本中,有MediaType
类。如果您想遵循DRY,它已经有正确的行:
public static final String APPLICATION_JSON_UTF8_VALUE = \"application/json;charset=UTF-8\";
因此,我使用这组与控制器相关的注释:
@RestController
@RequestMapping(value = \"my/api/url\",produces = APPLICATION_JSON_UTF8_VALUE)
public class MyController {
// ... Methods here
}
它在文档中已被标记为已弃用,但我遇到了这个问题,我认为它比在整个应用程序中的每个方法/控制器上复制粘贴上述行更好。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。