簡體   English   中英

國際化(語言環境)在 java spring boot 中不使用重音

[英]Internationalization (locale) not working with accents in java spring boot

我有一個 spring boot 應用程序,我使用兩種語言英語和法語。 我有我的文件 messages.fr 和 messages.en 作為參考,可以在 thymeleaf 的幫助下更改 html 文檔中的語言。

我的重音內容看起來像這樣的問題:例如“Créer un compte”(創建一個帳戶)它應該是:“Créer un compte”

在 Spring Boot 中完成此操作的最佳方法是什么? 感謝您的幫助..

請記住,我的屬性中有這個百里香配置

# INTERNATIONALIZATION (MessageSourceProperties)
spring.messages.always-use-message-format=false
spring.messages.basename=messages
spring.messages.cache-duration=-1
spring.messages.encoding=UTF-8
spring.messages.fallback-to-system-locale=true

#Thymeleaf configurations
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true 
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/

我在我的配置中使用這些 bean

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    LocaleChangeInterceptor.setParamName("lang");
    return localeChangeInterceptor;
}

@Bean
public LocaleResolver localeResolver() {
    final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
    cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
    return cookieLocaleResolver;
}

public void addInterceptors(InterceptorRegistry registry){
    registry.addInterceptor(localeChangeInterceptor());
}

我運行此代碼來測試內容類型

@RequestMapping(value = "/check", method = RequestMethod.GET)
@ResponseBody
public String plaintext(HttpServletResponse response) {
    response.setContentType("text/plain");
    esponse.setCharacterEncoding("UTF-8");
    return "àèääèäé";
}   

它返回相同的值 correclty:帶有口音的 àèääèäé

實際上,我過去有過類似的經歷,其中語言在 Spring Web 應用程序中沒有顯示重音。

在我在 github 上閱讀了一個關於它的小討論后,檢查這個鏈接

https://github.com/spring-projects/spring-boot/issues/5361

他們提到 java 在 ISO-8859-1 中有基本編碼,而 spring 在 UTF-8 中進行編碼,這會導致一些不兼容。 但是我從技術上不知道為什么,但我記得改變了我的屬性並且它起作用了。

你能嘗試改變你的屬性並替換嗎

spring.messages.encoding=UTF-8

經過

spring.messages.encoding=ISO-8859-1

我找到了另一個適合我的解決方案:

為了解決這個問題,只需在您的 WebConfig 類中添加messageSource.setDefaultEncoding("UTF-8")

完整的代碼片段如下所示:

@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

我在以下答案中找到了它: springboot-utf-8-doesnt-work-in-messages-properties

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM