Elegant way to get Locale in Spring Controller [duplicate]

一世执手 提交于 2020-01-02 01:07:12

问题


I'm looking for a cleaner way (in Spring 3.2) to get the current locale than explicitly calling LocaleContextHolder.getLocale() at the start of each Controller method. It has to be compatible with Java annotation, as I'm not using the XML config. Here's what I'm doing currently.

@Controller
public class WifeController {
    @Autowired
    private MessageSource msgSrc;

    @RequestMapping(value = "/wife/mood")
    public String readWife(Model model, @RequestParam("whatImDoing") String iAm) {
        Locale loc = LocaleContextHolder.getLocale();
        if(iAm.equals("playingXbox")) {
            model.addAttribute( "statusTitle", msgSrc.getMessage("mood.angry", null, loc) );
            model.addAttribute( "statusDetail", msgSrc.getMessage("mood.angry.xboxdiatribe", null, loc) );
        }
        return "moodResult";
    }
}

回答1:


In Spring 3.2 reference docs, section 17.3.3, Supported method argument types:

The following are the supported method arguments:

  • Request or response objects (Servlet API). Choose any specific request or response type, for example ServletRequest or HttpServletRequest.

    (...)

  • java.util.Locale for the current request locale, determined by the most specific locale resolver available, in effect, the configured LocaleResolver in a Servlet environment.

So all you'd need to do is receive an instance of Locale as an argument in every method:

@RequestMapping(value = "/wife/mood")
public String readWife(Model model, @RequestParam("whatImDoing") String iAm, Locale loc) {
    if (iAm.equals("playingXbox")) {
        model.addAttribute("statusTitle", msgSrc.getMessage("mood.angry", null, loc));
        model.addAttribute("statusDetail", msgSrc.getMessage("mood.angry.xboxdiatribe", null, loc));
    }
    return "moodResult";
}



回答2:


As an alternative, you can also autowire the HttpServletRequest

@Autowired
private HttpServletRequest request;

and then use request.getLocale() everywhere in your Controller.



来源:https://stackoverflow.com/questions/33049674/elegant-way-to-get-locale-in-spring-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!