Spring Controller @RequestMapping不支持非英语特殊字符

时间:2018-12-12 09:17:53

标签: java spring rest

我目前正在开发一个旧的Spring应用程序,该应用程序公开了用于移动设备的REST API。我需要为具有多种语言支持的Json请求创建一个新的REST服务。但是当我测试时,它仅支持英语。当我尝试其他语言时,它会给我??????相关数据的字符。

以下是我的配置类

@Configuration
@EnableScheduling
@ComponentScan(basePackages = "lk.test.com.controller")
public class ControllerConfig extends WebMvcConfigurationSupport {

    private static final Logger log = LoggerFactory.getLogger(ControllerConfig.class);

    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
        converters.add(getMappingJackson2HttpMessageConverter());
        addDefaultHttpMessageConverters(converters);
    }

    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(getObjectMapper());
        List<MediaType> mediaTypes = new ArrayList<MediaType>();
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(mediaTypes);
        return converter;
    }

    @Bean
    public ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
        objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        return objectMapper;
    }

}

以下是示例控制器方法

@RequestMapping(value = "send/push", method = RequestMethod.POST,consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Response sendPush(final @RequestBody CustomerExternalRequest request, HttpServletRequest servletRequest) {

        System.out.println(request.getPushMessage());
        Response response = new Response();
        return response;
    }

和相关请求对象

@Getter
@Setter
@ToString
public class CustomerExternalRequest extends Request{

    private String phoneNo;

    //push send
    private Boolean isOnlyToCurrenltyLoggedDevice;
    private String pushMessage;
    private String pushTitle;
}

我的Json请求

{"request":{"phoneNo":"+94776587745","isOnlyToCurrenltyLoggedDevice":true,"pushMessage":"测试","pushTitle":"测试"}} 

And this is my POSTMAN request

System.out.println(request);

打印??在控制台中

有人可以解决吗?谢谢。

1 个答案:

答案 0 :(得分:0)

最后找到了原因和解决方法。

当我尝试使用Spring Boot示例应用程序时,它起作用了。因为它具有嵌入式的tomcat服务器。就我而言,我使用了Eclipse Jetty插件。然后,我找到了一个更改编码类型的地方,并将其更改为UTF-8,现在可以正常使用了。

See the configuration screen shot here