<!-- 存储区域设置信息 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" /> <!-- 国际化资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:messages" /> </bean> <mvc:interceptors> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang" /> </bean> </mvc:interceptors>
在 controller 层或者 view 层均可调用
import org.springframework.web.servlet.support.RequestContext; import org.springframework.web.servlet.support.RequestContextUtils; import java.util.ResourceBundle; @Controller public class UserController { private static Logger logger = Logger.getLogger(UserController.class); @Autowired private UserService userService; /** * 从国际化资源配置文件中根据key获取value 方法一 * @param request * @param key * @return */ public static String getMessage(HttpServletRequest request, String key){ Locale currentLocale = RequestContextUtils.getLocale(request); String lang = currentLocale.getLanguage(); ResourceBundle bundle = ResourceBundle.getBundle("messages_"+lang, currentLocale); return bundle.getString(key); } /** * 从国际化资源配置文件中根据key获取value 方法二 * @param request * @param key * @return */ public static String getMessage2(HttpServletRequest request, String key){ RequestContext requestContext = new RequestContext(request); String value = requestContext.getMessage(key); return value; } @RequestMapping("/user") public ModelAndView getUsers(HttpServletRequest request){ List<VoUser> userList = userService.getUsers(); ModelAndView mv = new ModelAndView(); //从message中获取文字 //String showUserInfo = getMessage(request, "showUserInfo"); String showUserInfo = getMessage2(request, "showUserInfo"); mv.addObject("showUserInfo", showUserInfo); mv.addObject("userList", userList); mv.setViewName("user"); return mv; } }