Manoj Singh
Manoj Singh

Reputation: 951

Setting Locale in spring mvc Controller

I am facing which having different scenario.I have portal which saves the locale of the user in database.When The use get logging.I am getting user detail but I don't know how to set it in controller.

I know that we can use LocaleContextHolder to set the locale but I dont know how it will work with controller. Please will you give some example

This is my controller

@RequestMapping(value = "/showMotionProfile", method = RequestMethod.GET)
public String showMotionProfile(Model model, RedirectAttributes attributes,
        HttpServletRequest request) {

    Locale locale = LocaleContextHolder.getLocale();
    logger.info("---------->country"+locale.getCountry());

    logger.info("\n--------------showMotionProfile-----------\n");
    LocaleContextHolder.setLocale(locale.ITALIAN);
    logger.info("---------->country"+LocaleContextHolder.getLocale());

    return "showMotionProfile";
}

Please tell me if I have done right,cause It is not reflecting.

Thanks for help.

EDIT: I have this resolver config in my spring xml file:

<beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleR‌​esolver"> 
    <beans:property name="defaultLocale" value="en" /> 
</beans:bean> 
<interceptors> 
    <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeI‌​nterceptor">
        <beans:property name="paramName" value="locale"></beans:property> 
    </beans:bean> 
</interceptors> 

Can I use this by using @Autowired in my controller and setting the locale?

Upvotes: 2

Views: 10137

Answers (1)

Fritz Duchardt
Fritz Duchardt

Reputation: 11870

In general you are on the right track:

  • Add the SessionLocaleResolver to your application context.
  • Add the LocalChangeInterceptor to your application context, but note that this will only change the current locale, if "locale" is passed as request parameter to any of your web controllers.
  • Alternatively, inject the sessionLocalResolver into your Controller (using @Autowire or the application context XML) and call the setLocale method on it. That way you can pass it the locale value from your database.

Upvotes: 4

Related Questions