Сервис Spring Restful возвращает только английские символы, но другие символы, кроме английского, отображаются как '?'

Я построил веб-сервис Restful, используя Spring MVC 4.0.1, Контроллер возвращает ответ каждого английского слова и символов в браузере. Но каждый отдельный персонаж, который NON-ENGLISH возвращаются как ?, Например, для नेपाल (Непальское слово произношения Nepal) оно возвращается как ????,

Вот мой RestController учебный класс:

@RestController
public class TestController {

private final ApplicationContext applicationContext;

@Autowired
public TestController(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
}

@RequestMapping(value = {"/test/{test}"})
public String getLatestCategoryNews(
        @PathVariable("categories") String categories,
        @RequestParam String test)
{
    return "नेपाल";
}
}

Вот мой dispatcher-servlet.xml:

     <?xml version='1.0' encoding='UTF-8' ?>
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.0.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

<context:component-scan base-package="com.billions.news.web.controller"/>
<mvc:annotation-driven />

Вот мой web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>    
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

Вот мой application-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd>
    <context:property-placeholder location="application.properties"/>
    <context:component-scan base-package="com.test.web"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />

Когда я возвращаю reponse, преобразуя его в строку json с помощью json-io, в консоли IDE я могу получить нужный текст. Но когда я получаю ответ в Браузере, он преобразуется обратно в "????". Это меня сильно раздражает.

Я использовал следующие тоже @RequesMapping:

method = RequestMethod.GET,
        produces = MediaType.ALL_VALUE

Но он все еще производит тот же ответ с "????".

Я пробовал множество решений в Интернете, включая filters, Но никто из них не помог.

Я использую Tomcat в качестве сервера.

Есть ли способ, чтобы я мог получить ответ на любом языке, в том числе на английском языке в spring-mvc restcontroller.

РЕДАКТИРОВАТЬ:

После решил вопрос: все, что мне нужно было сделать, это заменить

<mvc:annotation-driven />

с

    <mvc:annotation-driven >
    <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF-8" />
            </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

1 ответ

Решение

Во -первых, в методе вашего контроллера getLatestCategoryNews ты возвращаешься String, это значит, что весна выберет одного из зарегистрированных HttpMessageConverters который в вашем случае будет StringHttpMessageConverer ( вот документ), который будет отвечать за написание возвращенного String,

По умолчанию кодировка для этого StringHttpMessageConverer

конструктор по умолчанию, который использует "ISO-8859-1" в качестве кодировки по умолчанию.

Вы должны переопределить кодировку этого конвертера сообщений.

просто зарегистрируйте бин:

<beans class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF-8" />
            </bean>
        </array>
    </property>
</beans>

ОБНОВЛЕНИЕ от меня

Вы также должны установить кодировку проекта в maven pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Обновление от @Computergodzilla

Я должен был сделать, чтобы удалить <mvc:annotation-driven/> с

<mvc:annotation-driven>
   <mvc:message-converters>
      <bean class="org.springframework.http.converter.StringHttpMessageConverter">
         <property name="supportedMediaTypes" value="text/html;charset=UTF-8" />
      </bean>
   </mvc:message-converters>
</mvc:annotation-driven>
Другие вопросы по тегам