The JSF framework on which XPages are built has built-in functions to display messages to users. You can see this in use if you add a validator to a field and disable clientside validation in the application properties: if the validation fails, a message is added to the FacesContext object that can be displayed on screen by including a Display Errors (<xp:messages>) control.
It is also possible to add your own custom messages by using the facesContext.addMessage() method. This was described by Tommy Valand on his blog.
A problem with the default JSF messages implementation is that the messages are gone if you open another page or redirect the user to another page. Consider for instance the case that you show a list of items to users on an XPage (using a data table or view panel) and allow a user to create a new item by redirecting him to another XPage containing a form. After the user has saved the form, you want to show him a confirmation message that the item was successfully saved or show him the ID of the created document. To be able to do this you need a way to store the messages between pages.
After some searching I found a way to do so by implementing a so called phase listener. This is basically a plugin you add to an application that allows you to execute your own custom code on predetermined phases in the JSF request lifecycle. The MultiPageMessagesSupport class from the article attaches itself to certain phases to temporarily store the messages in the sessionScope retrieve them when a (new) page is rendered.
To use this method you need to perform the following steps:
- Create a new Java class in the “Code” section of your application (assuming you’re using 8.5.3). Call it MultiPageMessagesSupport, set the default package and add this code. The class file in the link uses the package “myPackage”.
- Add the phase-listener from the newly created Java class to the faces-config.xml file of your application:
- Include an <xp:messages> control on all pages to show the messages to your users:
var type = javax.faces.application.FacesMessage.SEVERITY_INFO; var msg = "this is my message"; facesContext.addMessage(null, new javax.faces.application.FacesMessage(type, msg, ""));
The demo database can be downloaded here.