竞争无处不在,青春永不言败!专业撸代码,副业修bug

Talk is cheap , show me the code!



i18n 国际化

  <!-- 存储区域设置信息 -->
    <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>
向springmvc.xml配置文件中添加

在 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;
    }
    
}
Controller 层调用

 

posted @ 2018-05-18 09:25  云雾散人  阅读(192)  评论(0编辑  收藏  举报

Your attitude not your aptitude will determine your altitude!

如果有来生,一个人去远行,看不同的风景,感受生命的活力!