簡體   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