繁体   English   中英

春季-使用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中的maven中确实有utf-8设置:

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

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

解决了。

我不将文件转换为String,而是发送字节数组,让客户端决定(基于标头中的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));     
}   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM