Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

jsf 2 - Creating FacesMessage in action method outside JSF conversion/validation mechanism?

I'm currently learning about jsf 2.0 from core jsf 2.0 book + glassfish + cdi.

I would like to ask a question about handling validations that are not defined in the jsf pages or managed/named beans with bean-validation-framework. I got these tiers in my head :

  • 1) ui tier / jsf pages
  • 1.5) jsf managed / named beans (i use 1.5, because i think it's still tightly coupled with the jsf tier, like the backing beans)
  • 2) business logic tier (which are clean from jsf stuffs / imports, doing only pure business logic stuffs)
  • 3) persistence tier

I imagine tier 1.5(jsf bean) initializing and calling tier 2(business logic objects), supplying arguments when calling business methods, fetching result, populating the result into jsf bean properties, so that the ui could render correctly.

What im curious is the fact that the tier 2(business logic objects) could do validations on the supplied arguments, or validating data, etc, and could throw exceptions or error objects.

I think i could handle the exceptions and get the error objects in the tier 1.5(jsf managed beans), but how am i supposed to display the error in the rendered pages ? I cant seem to find it from the book im reading, but i'm hoping there's a way to create a global error message and somehow could inject it into somewhere so that it gets rendered by the tag ?

Thank you !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use FacesContext#addMessage() to add a FacesMessage to the context programmatically.

FacesContext facesContext = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage("This is a message");
facesContext.addMessage(null, facesMessage);

When you set the client ID argument with null, it will become a global message. You can display and filter them using <h:messages />

<h:messages globalOnly="true" />

The globalOnly="true" will display only messages with a null client ID.

You can however also specify a specific client ID.

facesContext.addMessage("formid:inputid", facesMessage);

This one will then end up in

<h:form id="formid">
    <h:inputText id="inputid" />
    <h:message for="inputid" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...