Java 怎么获取JSF消息资源

2019年8月14日22:00:31Java 怎么获取JSF消息资源已关闭评论 187 1667字阅读5分33秒

1.简介

Java 怎么获取JSF消息资源?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        String key = "tah1986.com";
        System.out.println(getMessageResource(key));
    }
    private static final Logger log = Logger.getLogger(BundleUtil.class);
    
    public static String getMessageResource(String key, Object[] arguments) {
        try {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            String messageBundleName = facesContext.getApplication()
                    .getMessageBundle();
            Locale locale = facesContext.getViewRoot().getLocale();
            ResourceBundle bundle = ResourceBundle.getBundle(
                    messageBundleName, locale);
            String resourceString = bundle.getString(key);
            MessageFormat format = new MessageFormat(resourceString,
                    facesContext.getViewRoot().getLocale());
            return format.format(arguments);
        } catch (MissingResourceException e) {
            log.error("###########################");
            log.error(
                    "Error al levantar la key: " + key + "\n"
                            + e.getMessage(), e);
            log.error("###########################");
            return "Key no localiza...";
        }
    }
    
    public static String getMessageResource(String key) {
        FacesContext facesContext = FacesContext.getCurrentInstance();

        try {
            String nameFileI18N = facesContext.getApplication()
                    .getMessageBundle();
            ResourceBundle bundle = ResourceBundle.getBundle(nameFileI18N,
                    facesContext.getViewRoot().getLocale());
            return bundle.getString(key);

        } catch (MissingResourceException e) {
            log.error("###########################");
            log.error(
                    "Error al levantar la key: " + key + "\n"
                            + e.getMessage(), e);
            log.error("###########################");
            return "Key no localiza...";
        }
    }
}

 
继续阅读
编程十万个怎么办