Skip to content
Advertisement

Spring save locale and change locale when user logs in

I have a spring application that I want users to be able to change the preferred locale. Currently users can change the locale for the current session but I want to be able to save the users option so that whenever they log in, the saved locale is used if one exists. I have a mysql database which I’m using to store the user locale preference. I have created a custom AuthenticationSuccessHandler to handle changing the locale to the saved locale, which works for a user where I have already saved the locale to the database. However, the bit I don’t know how to do is save the locale when the option is changed. The code is as follows:

JavaScript

SecurityConfig class:

JavaScript

AuthenticationSuccessHandler class

JavaScript

Part of html page that shows the language change options:

JavaScript

Javascript that changes the language option:

JavaScript

Advertisement

Answer

You can implement LocaleResolver interface to bind users Locale to database. Sample implementation “ApplicationLocaleResolver.java” is below

JavaScript

I assume your userService has a method that save users local to db. I prefer userService.saveUsersPreferedLocaleOption(userName, locale); You can change it.

Then you can replace localeResolver bean definition as below.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement