Server Side Validation in Liferay

Validation is an essential part of any framework or tool. Validation can be done at client side (through JavaScript) and server side. In this article, we will see how to do server side validation for Liferay portlet.

For simplicity, I choose SpringMVC portlet to demonstrate server side validation. You can use this blog to perform validation on Liferay MVC portlet too.

I would recommend looking at index page ‘A Complete Liferay Guide‘ to browse all topics about liferay.

Refer my previous blog on How to Create Spring MVC Portlet in Liferay  to create SpringMVC portlet. Give project name as server-side-validation-test. Once it is created, it will looks like as per below screenshot.
Server Side Validation in Liferay - Project Structure
You can observe the following things
  • Controller class is ServerSideValidationTestViewController which resides under com.serverside.validation.test.controller package.
  • I have create two jsps. profile.jsp and success.jsp
  • In profile.jsp, we will place some fields that needs to be validated.
  • Once its validated it should show success message either on same page(profile.jsp) or new jsp( success.jsp).
  • In case if user inputs are not validated, then we will show error messages on profile.jsp page.
Now let us start constructing profile.jsp. Add following code in it.





Explanation:-

  • First two lines are taglib entries for portlet and liferay-ui
  • the next line is <portlet:defineObjects>. Because of this tag, we can access implicit objects in JSP like RenderRequest etc.
  • In next line, we have created actionURL to call controller’s action method on submitting form. We have passed this actionURL (represented by var variable in  <portlet:actionURL> tag) to action attribute of <form>.
  • Next 3 lines are liferay-ui tag which shows error message if user inputs are not validated.I will explain this later in this blog.
  • At the last we have form with 3 text box (name, age and email) with submit button.

Server Side Validation

Add the code in controller so that it will looks like as per below snippet



Explanation:-

  • First we have defined log with the help of Liferay utility class LogFactoryUtil.
  • Then we have defined default render method which simply return view (profile.jsp)
  • Next to it, we have defined action method, which simply read the values that user entered as request parameter.
  • Then we are validating for null or empty value. If the value is null or empty, we are calling SessionErrors.add(request,”name-is-required”).
  • This line of code will say that add the error with key “name-is-required” in SessionErrors object in request scope.
  • To show the error message in jsp we are using liferay-ui tag and giving respective key and message. So if matching key is found then its message will be displayed otherwise no input. That is the reason on first time this jsp (profile.jsp) render, we are not getting any error message.
  • This way we can set the error key in controller (Based on validation condition) and in JSP,if the matching key is found then respective error message will be displayed.
Now let us see the practical. Deploy the portlet and you will found the profile as per below screenshot.
Server Side Validation in Liferay - profile-jsp-render
We have keep the validation for null or empty string of all three (Name, Age and Email) value. So If we left blank any of these value and click on submit, then it will show error message as per below screenshot.
Server Side Validation in Liferay - profile-jsp-error-message

How it works:- 

  • First I have just click on Submit button without giving any value.
  • Form has been submitted to controller’s action method (submitProfileAction) without any value.
  • In action method we are checking if these values are blank or null then we are adding error key into SessionErrors object.
  • After Action method’s execution finished, it will call default render method and from default render method, profile.jsp will be rendered.
  • In jsp file we have defined tag <liferay-ui:error>  which will actually check whether the matched error key is present (which we have set in controller’s action method in request scope) then it will show message (defined by message attribute of respective <liferay-ui:error> tag).
Now if user’s inputs are validated, then we have to acknowledge that all your data are successfully saved. For that we will modify our controller’s code so that it will looks like as below snippet.



Explanation:-

  • We have create one Boolean variable isErrorOccured and setting its value true in case if we found null or empty value (of name,age and email) in 3 if conditions block.
  • At the end we are checking if the value of isErrorOccured is false (mean no error occurred and all user inputs are validated correctly) then we are setting success message key by SessionMessages.add(request,”profile-saved-successfully”).
  • It means we are storing success message key “profile-saved-successfully” in SessionMessages object in request scope
  • Note that we are using SessionErrors to store error message and SessionMessages for success messages.
  • After that we are calling response.setRenderParameter(“action”,”showSuccess”).
  • By default, once action method execute, the default render method will be called. But if we want to call specific render method then we have to set action key of that render method through response.setRenderParameter method.
  • We have created one render method with action key “showSuccess” just below the action method.
  • To call this render method from action method, we are setting the value of render parameter action same as action key of render method (“showSuccess”).
  • And this render method will render success.jsp.
  • This way, if any error occurs then the default render method will be called and if all user inputs are validated successfully then the second render method (with the action key “showSuccess”) will be called.
Now add following code into success.jps  file.

 
Explanation:-

  • First line is the tag-library declaration for liferay-ui 
  • In second line we have called <liferay-ui:success> which will work similar way as <liferay-ui:error>. We are passing key and message
  • If any matching success key is found in request scope then success message will be shown (defined in message attribute of <liferay-ui:success>)

Now let us do some practical. Deploy the above code and give all values in profile page and submit success message. You will get success message as per below screenshot.

Server Side Validation in Liferay - success-message

Show error message based on Exception :-

Some times, we may required to show error message based on some exception occurred. So Instead of error key which we are setting in action method, we will just set the type of exception in SessionErrors  object. Let see it in action.

To understand it properly, we will create two custom Exception class under called Exception1.java and Exception2.java under com.serverside.validation.test.exception package. The project structure will looks like below screenshot.

Server Side Validation in Liferay - Project-Structure-with-exception

To understand it properly, I have done code changes in controller so that it will looks like below snippet.

Explanation:-

  • In action method, I have commented out the validation logic and generating one random number between 0 to 10.
  • Throwing the exception (either Exception1 or Exception2 ) based on the generated value is odd or even.
  • In catch block, setting the error key by calling overloaded add  method. This method is taking 3 values as parameter, first is the actionRequest , second is the key (for which we are passing class name of exception) and third is the value of key as object (for which we are passing exception object).
  • At the last, we are not setting any render parameter so that the default render method will be called and profile.jsp will be rendered.
I added following two line in profile.jps file

 
Here instead of key,  we are passing the name of exception class (Exception1 and Exception2) in exception attribute of <liferay-ui:error> tag.

Let us see this in action. Deploy the portlet and it will show profile.jsp page. Now just click on Submit button and you will get message either for Exception1 or Exception 2 as per below screenshot.

Server Side Validation in Liferay - exception-as-keyIf you keep clickin Submit button, it will show message for either Exception1 or Excepiotn 2. This behavior is random as we are checking whether the random number is odd or even.
You may do some more testing by setting some more complex validation. Its also possible to pick the error or success message from language property file instead of hard code. 

Summing Up

  • Server side validation in Liferay must be performed in Portlet.
  • Any error occurs during execution need to place in SessionErrors object with key
  • This key will be used to show error message in portlet JSP by <liferay-ui:error> tab.
  • Message passed to <liferay-ui:error> can be multilingual by defining language key in it.

I would recommend looking at index page ‘A Complete Liferay Guide‘ to browse all topics about liferay.

Download Source

Download Source

 

Share This Post

13 Comments - Write a Comment

  1. Hi Nilang,
    Greetings of the day!

    Do you have any sample application portlet configurable preferences using SpringMVC Portlet.
    Thanks in advance.
    Thanks,
    Anki

    Reply
    1. Hi Ankireddy,

      As of now I don’t have but I am planning to write blog on configuration / preference for both Liferay MVC and Spring MVC soon. So stay tune and join Tech Blog.

      Regards
      Nilang

      Reply
    1. Hi Anindya Mallik,

      First of welcome to Tech blog. What I understand from your question is that you are asking to show the values which were added (before form submission), after the server side validation execute. Well that is possible. In the catch block, you can store the values in request scope and retrieve it on jsp so that the values will be visible even after validation done.

      Regards
      Nilang

      Reply
  2. How do I clear Session errors/messages if I make Ajax calls using Spring MVC portlet/controller? I tried using SessionErrors.clear or SessionMessages.clear, they work with LiferayPortlet but do not seem to with SpringMVC. Any thoughts?

    Reply
  3. Good explanation. Only I have one correction to do:

    Instance of:

    email == null || “”.equalsIgnoreCase(email)

    This is more clean:

    Validator.isNull(email)

    Reply

Post Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.