在h:message中设置自定义消息

时间:2019-03-20 17:55:46

标签: jsf-2

我正在尝试使用h:message在每个InputText前面放置一条自定义消息。

我的问题是我找不到设置消息的方法。

这是HTML:

<h:inputText id="_inputValue" binding="#{bean.inputtext}"/>
<h:message for="_inputValue" binding="#{bean.message}"/>
<h:commandButton value="validate" actionListener="#{bean.action}"/>

在Managed Bean中,我尝试了不同的方法,但仍然没有显示消息:

获取HtmlInput组件并设置其ValidatorMessage,

public void action(ActionEvent event)
{
	inputtext.setValidatorMessage("ERROR");
}

然后我也尝试使用其clientID设置消息。

public void action(ActionEvent event)
{
	//Get message id
	String messageId = message.getClientId();
		
	//Get context
	FacesContext context = FacesContext.getCurrentInstance();
		
	//Create message
	FacesMessage fmessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message:", "this is an error message !");
		
	//Add message
	context.addMessage(messageId, fmessage); 
}

在这个阶段,令我惊讶的是,没有一种简单的方法可以在验证bean之后在Java的h:message中设置一条消息。

我正在使用JSF 2.2

解决方案:

收到评论后,找到了以下解决方案,

  • 遵循常规的JSF验证
  • 使用验证器。

<h:inputText id="_inputValue" binding="#{bean.inputtext}" validator="validatorName"/>
<h:message for="_inputValue" binding="#{bean.message}"/>
<h:commandButton value="validate" actionListener="#{bean.action}"/>

然后,验证器将创建一个FacesMessage并将其用于throw声明中。抛出新的ValidatorException(message)。由于jsp消息组件通过for = _inputText链接到输入文本,因此将显示验证程序消息。

@FacesValidator("validatorName")
public class MyValidator implements Validator 
{
    //[JOB OVERRIDE]
    @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException 
    {
        FacesMessage message = new FacesMessage("type of validation that failed.", "detailed cause of failure.");
        message.setSeverity(FacesMessage.SEVERITY_ERROR);

        throw new ValidatorException(message);
    }
}

警告:

  • 请注意,验证器不是Bean且未在CDI中注册,这就是为什么我们使用Validator =“ validatorName”而不是validateator =“#{validatorName}”的原因。

  • 如果将验证器转换为Bean,则删除@FacetValidator并替换为@Named(“ validatorName”),然后在jsp页面中使用validateator =“ {validatorName}”。

0 个答案:

没有答案
相关问题