如何根据条件显示h:消息?

时间:2013-02-16 11:00:48

标签: jsf jsf-2 validation multilingual

我正在制作多语言网站,我在一个字段中使用Validator。

验证后,我收到响应为err002, err003,根据此错误,我将在消息格式中显示相应的错误。所以我计划的是下面的内容。

我所拥有的是<h:message for="password">

我想做的是如下。

if (message is err002) {
    show message of err002 from the properties file.
    #{msg['err002']}
}
if (message is err003) {
    show message of err003 from the properties file.
    #{msg['err003']}
}

知道如何完成这项工作吗?

其实我想做的是用两种语言显示错误信息。我所拥有的是会话bean中的语言代码,但我无法在验证器中检查语言代码。

任何想法/建议如何做到这一点都会很棒。


编辑1

面-config.xml中

<application>
    <locale-config>
        <default-locale>zh_CN</default-locale>
    </locale-config>
    <resource-bundle>
        <base-name>resources.welcome</base-name>
        <var>msg</var>
    </resource-bundle>
</application>

LanguageBean.java

@ManagedBean(name = "language")
@SessionScoped
public class LanguageBean implements Serializable {

我拥有的属性文件

welcome.properties welcome_zh_CN.properties

1 个答案:

答案 0 :(得分:3)

您可以在验证器方法中轻松实现它。像

一样使用它
@FacesValidator("passwordValidator")
public class PasswordValidator implements Validator {

    String err1, err2, err3;

    public PasswordValidator() {
        ResourceBundle bundle = ResourceBundle.getBundle("msg", FacesContext.getCurrentInstance().getViewRoot().getLocale());
        err1 = bundle.getString("err1");
        err2 = bundle.getString("err2");
        err3 = bundle.getString("err3");
    }

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String pass = (String) value;
        FacesMessage msg;
        if(/*some condition*/) {
            msg = new FacesMessage(err1);
        } else if(/*other condition*/) {
            msg = new FacesMessage(err2);
        } else {
            msg = new FacesMessage(err3);
        }
        if(msg != null) {
            throw new ValidatorException(msg);
        }
    }    
}

使用

进行查看
<h:inputText id="password" validator="passwordValidator" .../>
<h:message for=password .../>