Java 怎么获取JSF消息资源

2019年8月14日22:00:31 评论 29

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

 

3.总结

示例代码演示了 Java 如何获取JSF消息资源,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: