在 Spring Controller 中获取 Locale 的优雅方式

Elegant way to get Locale in Spring Controller

我正在寻找一种比在每个控制器方法开始时显式调用 LocaleContextHolder.getLocale() 更简洁的方法(在 Spring 3.2 中)来获取当前语言环境。它必须与 Java 注释兼容,因为我没有使用 XML 配置。这是我目前正在做的事情。

@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";
    }
}

Spring 3.2 reference docs 中,第 17.3.3 节,支持的方法参数类型:

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.

所以您需要做的就是在每个方法中接收一个 Locale 的实例作为参数:

@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";
}

作为替代方案,您还可以自动装配 HttpServletRequest

@Autowired
private HttpServletRequest request;

然后在控制器中的任意位置使用 request.getLocale()