如何在Spring Framework 3中的控制器内翻译文本?

new*_*bie 22 spring localization internationalization

我需要发送电子邮件确认,所以现在我必须本地化发送的消息.我在春天初始化了i18n,现在它在jsp页面中运行得很好,但是如何在我的控制器中使用它呢?

Daf*_*aff 46

如果您使用带注释的控制器,则可以自动装配MessageSource并添加请求的语言环境,如下所示:

@Controller
@Scope("request")
public class MailController
{
    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = "/mail/send", method = RequestMethod.GET)
    public ModelAndView sendEmail(Locale locale)
    {
        String[] args = { "Mr.", "X" };
        // E.g. message.code="Dear {0} {1}"
        String mailmessage = messageSource.getMessage("message.code", args, locale);
        // Do something
        return new ModelAndView();
    }
}
Run Code Online (Sandbox Code Playgroud)