Spring - 使用 UTF-8 从文件加载

Spring - Load from file with UTF-8

我在使用 Spring 加载 UTF-8 文件时遇到问题。

这对我有用:

我有属性文件,保存为 UTF-8 格式的内容

global.variable.try=This is product variable
cache.location.filename.regions=regions
hacky.carky=éíáščýéíšž hehe haha hoho +íšářá

在我的控制器中,我通过两种方式访问​​它

@Controller
@RequestMapping(value = "/aserver")
public class AServerController {

@Value("${hacky.carky}")
    private String hackyCarky;  

    @RequestMapping(value = "/hackycarky", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object hackycarky(ServletRequest servletRequest, ServletResponse response) throws MalformedURLException, IOException{
        return hackyCarky;
    }   

    @RequestMapping(value = "/regions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object regions(ServletRequest servletRequest, ServletResponse response) throws MalformedURLException, IOException{
        String filePath = "c:\prace\eclipse workspace\czechtraditions\server\src\main\resources\server-general.properties";
        return new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);     
    }   
}

如果我访问 /aserver/hackycarky,它会给出所需的输出:

éíáščýéíšž hehe haha hoho +íšářá

但是如果我访问 /aserver/regions,输出如下:

global.variable.try=This is product variable
cache.location.filename.regions=regions
hacky.carky=���??���?? hehe haha hoho +�?�?�

PS :我不需要访问属性文件,这只是测试用例,可以肯定的是,文件格式正确 - 因此可以按预期使用 @Value("${hacky.carky}")

两种情况下的响应头是一样的,有这个属性

Content-Type:application/json;charset=UTF-8

我确实在 web.xml 中设置了针对 utf-8 的过滤映射:

<filter>
    <filter-name>encoding-filter</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>encoding-filter</filter-name>
    <url-pattern>/rest/*</url-pattern>
</filter-mapping>

我的 pom.xml 中确实有 utf-8 设置 for maven :

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

完整地址示例为http://localhost:8080/czechtraditions-server/rest/aserver/regions

已解决。

我不将文件转换为字符串,我发送字节数组并让客户端决定(基于 header 中的 content-type)如何处理它并且它工作正常。

@RequestMapping(value = "/regions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Object regions(ServletRequest servletRequest, ServletResponse response) throws MalformedURLException, IOException{
    String filePath = "c:\prace\eclipse workspace\czechtraditions\server\src\main\resources\server-general.properties";
    return Files.readAllBytes(Paths.get(filePath));     
}