在Spring Controller中获取语言环境的绝佳方法 [英] Elegant way to get Locale in Spring Controller

查看:596
本文介绍了在Spring Controller中获取语言环境的绝佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

以下是受支持的方法参数:

The following are the supported method arguments:

  • 请求或响应对象(Servlet API).选择任何特定的请求或响应类型,例如ServletRequest或HttpServletRequest.

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

(...)

(...)

java.util.Locale ,实际上是由Servlet环境中可用的最特定的语言环境解析器确定的.

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实例作为参数:

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

这篇关于在Spring Controller中获取语言环境的绝佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆