Displaying Messages and Errors
Step 2 of 3
To display feedback to users properly, you must edit your portlet classes to use
Liferay DXP’s SessionMessages
and SessionErrors
classes. These classes collect
messages that the view layer shows to the user through a tag.
You’ll add these messages to code that runs when the user triggers a system
function that can succeed or fail, such as creating, editing, or deleting a
Guestbook or Guestbook entry. This happens in action methods. You must update
these methods to handle failure and success states in GuestbookPortlet.java
and GuestbookAdminPortlet.java
. Start by updating addEntry
and deleteEntry
in GuestbookPortlet.java
:
-
Find the
addEntry
method inGuestbookPortlet.java
. In the firsttry...catch
block’stry
section, and add the success message just before the closing}
:SessionMessages.add(request, "entryAdded");
This uses Liferay’s
SessionMessages
API to add a success message whenever a Guestbook is successfully added. It looks up the message you placed in theLanguage.properties
file and inserts the message for the keyentry-added
(it automatically converts the key from camel case). -
Below that, in the
catch
block, find the following code:System.out.println(e);
-
Beneath it, paste this line:
SessionErrors.add(request, e.getClass().getName());
Now you not only log the message to the console, you also use the
SessionErrors
object to show the message to the user.
Next, do the same for the deleteEntry
method:
-
After the logic to delete the entry, add a success message:
SessionMessages.add(request, "entryDeleted");
-
Find the
Logger...
block of code in thedeleteEntry
method and after it, paste this line:SessionErrors.add(request, e.getClass().getName());
-
Hit [CTRL]+[SHIFT]+O to import
com.liferay.portal.kernel.servlet.SessionErrors
andcom.liferay.portal.kernel.servlet.SessionMessages
. Save the file.
Well done! You’ve added the messages to GuestbookPortlet
. Now you must update
GuestbookAdminPortlet.java
:
-
Open
GuestbookAdminPortlet.java
and look for the same cues. -
Add the appropriate success messages to the
try
section of thetry...catch
inaddGuestbook
,updateGuestbook
, anddeleteGuestbook
, respectively:SessionMessages.add(request, "guestbookAdded"); SessionMessages.add(request, "guestbookUpdated"); SessionMessages.add(request, "guestbookDeleted");
-
In the
catch
section of those same methods, findLogger.getlogger...
and paste theSessionErrors
block beneath it:SessionErrors.add(request, pe.getClass().getName());
-
Hit [CTRL]+[SHIFT]+O to import
SessionErrors
andSessionMessages
. Save the file.
Great! The controller now makes relevant and detailed feedback available. Now all you need to do is publish this feedback in the view layer.