Проблема кодирования UTF-8 в Spring MVC
У меня есть Spring MVC bean, и я хотел бы вернуть турецкий символ, установив кодировку UTF-8. но хотя моя строка "şŞğĞİıçÇöÖüÜ", она возвращается как "?????? çÇöÖüÜ". а также когда я смотрю на страницу ответов, которая является страницей интернет-исследователя, кодировка - это западноевропейская 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;
}
Ответы
Ответ 1
Я понял это, вы можете добавить к запросу mapping results = "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);
}
см. это сообщение в блоге для получения более подробной информации о решении
Ответ 2
в вашем XML-контексте сервлета диспетчера, вам нужно добавить свойство
"<property name="contentType" value="text/html;charset=UTF-8" />"
на вашем viewResolver bean.
мы используем freemarker для просмотров.
он выглядит примерно так:
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
...
<property name="contentType" value="text/html;charset=UTF-8" />
...
</bean>
Ответ 3
Преобразуйте строку JSON в UTF-8 самостоятельно.
@RequestMapping(value = "/example.json", method = RequestMethod.GET)
@ResponseBody
public byte[] example() throws Exception {
return "{ 'text': 'äöüß' } ".getBytes("UTF-8");
}
Ответ 4
Есть несколько похожих вопросов: Spring проблема с кодировкой ответов MVC, Пользовательский HttpMessageConverter с @ResponseBody, чтобы делать вещи 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) для другого типа содержимого.
Ответ 5
Я решил эту проблему, выведя полученный тип возврата в первый метод запроса GET. Важная часть здесь -
produces="application/json;charset=UTF-8
Итак, каждый, как use/account/**, Spring, вернет тип приложения /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);
}
}
Таким образом, вам не нужно настраивать для каждого метода в вашем контроллере, вы можете сделать это для всего класса. Если вам требуется больше контроля над конкретным методом, вам нужно только вывести тип возвращаемого содержимого.
Ответ 6
Также добавьте в свой beans:
<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/>
, это должно быть после beans.