Search code examples
javaspringspring-mvcspring-bootthymeleaf

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


I have a spring boot application where I use two languages English and French. I have my file messages.fr and messages.en as references to change the languages in the html documents with the help of thymeleaf.

The problem that my accented stuff are looking like this: for example "Cr�er un compte" (create an account) It should be: "Créer un compte"

What is the best way to go through this in spring boot? thank you for your help..

keep in mind that I have this thymeleaf configuration inside my properties

# 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/

I am using these beans in my configuration

@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());
}

I run this code to test the content-type

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

it returns the same value correclty: àèääèäé with accents


Solution

  • Actually I had similar experience in the past where Languages doesn't show up with accents in Spring web application.

    After I read a small discussion in github about it, check this link

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

    They was mentionning that java has base encoding in ISO-8859-1 and spring do it in UTF-8 which cause some incompatibilty. However I dont know technically why, but I remember changing my properties and it worked.

    Can you try to change your properties and replace

    spring.messages.encoding=UTF-8
    

    by

    spring.messages.encoding=ISO-8859-1