Tuesday, May 20, 2014

Liferay MVC Portlet Form Submission

Introduction:

Generally when we work with Portlet Application development we need to submit form and display the data in JPS page or we need to store the data into database.

In this article I only explain simply submit the form data to portlet action methods and then display submitted data in JSP pages.

In web application we will use Html form to post or pass the data to server side. We have another way to send the data to server is as request parameters in URL. In general Form is the way to take user inputs and send to the server side.

Note:

In the URL request if we send any data then it will be always a simple string values.
Forms also submitted the data as URL query string, this we can observe when we use GET method in forms.

Before Start this article Please have a look into following article


Well we are aware of Liferay MVC Portlet Development.

Environment:

Liferay IDE 2.x+Eclipse (Kepler) +Liferay Plugins SDK 6.2+Tomcat 7.x Liferay Portal Bundle

Steps:
  1. Create Simple MVC Portlet Using Liferay IDE
  2. Define HTML Form in JSP page
  3. Capture Form Data in Portlet Class Action Method
  4. Display Submitted Data in other JSP Page.

Create Simple MVC Portlet Using Liferay IDE

In the first steps we need to create Liferay MVC Portlet with help of Liferay IDE.

Follow the article and create Simple Liferay MVC Portlet.


Define HTML Form in JSP page

Once we done above step then we will create simple html form in JSP page and we will use different form elements to send the data to server.

We have following form elements to send data to server/portlet action method


input text , input radio , input check box, text area , input file and select box

Note:

We will use different form elements for different purpose

Example:

Single selection we will use Radio
Multiple selected options we will use check box or multi select box
For text input we will use text fields,
If more text then we will use text area
Send file then we will use file input element


Example Html Form in JSP page


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />

<portlet:actionURL var="addStudentActionURL" windowState="normal" name="addStudent">
</portlet:actionURL>

<h1>Student Form</h1>

<form action="<%=addStudentActionURL%>" name="studentForm"  method="POST">
<b>First Name</b><br/>
<input  type="text" name="<portlet:namespace/>firstName" id="<portlet:namespace/>firstName"/><br/>
<b>Last Name</b><br/>
<input type="text" name="<portlet:namespace/>lastName" id="<portlet:namespace/>lastName"/><br/>
<b>Exam Fee</b><br/>
<input type="text" name="<portlet:namespace/>examFee" id="<portlet:namespace/>examFee"/><br/>
<b>Gender</b><br/>
<input type="radio" name="<portlet:namespace/>sex" value="male">Male<br>
<input type="radio" name="<portlet:namespace/>sex" value="female">Female<br/>
<b>Subjects Obtained</b><br/>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Maths">Maths<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Physics">Physics<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Chemistry">Chemistry<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Bio Technology">Biotechnology<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Computer Science">Computer Science<br>
<b>Academic Year</b><br>
<select name="<portlet:namespace/>acadamicYear">
  <option value="I Year">I Year</option>
  <option value="II Year">II Year</option>
  <option value="III Year">III Year</option>
  <option value="IV Year">IV Year</option>
</select><br>
<b>Address</b><br/>
<textarea rows="4" cols="50" name="<portlet:namespace/>address">
</textarea><br/>
<input type="submit" name="addStudent" id="addStudent" value="Add Student"/>
</form>


Note:

We should append <portlet:namespace/> to each input “name” attribute  then only portlet action class consider it in request parameter otherwise it will be ignored by portlet action class.

 This behavior we can observe from Liferay 6.2 version. I already explained regarding to this in previous articles.

In the form “action” attribute we need to give action URL so that form input data will be available in respective action method.

We should specify the “method” attribute to form then only form will be submitted to respective portlet action method.

Capture form Data in Portlet Class Action Method

We will get form input data or request parameter values in the following ways.

request.getParamter(“inputName/requestParameterName”)

We will use above method so that we can get values in portlet class action method

Example:


Form Input Element

<input  type="text" name="<portlet:namespace/>firstName" id="<portlet:namespace/>firstName"/><br/>

Get the value in Action Method

String firstName=actionRequest.getParameter("firstName");


Note:

We already know all request parameter values and form input values always string values when it reaches action method or server side. Based on our expected type we need to type cast the string values.

If we use above method we need to type cast values when we want specific data type.

ParamUtil Class

Liferay have given ParamUtil class which consists of many methods and we will use those methods to capture request parameter values or form input values.

Example:


Form Input Element

<input  type="text" name="<portlet:namespace/>firstName" id="<portlet:namespace/>firstName"/><br/>

Get the value in Action Method

String firstName=ParamUtil.getString(actionRequest,"firstName");


This class has different methods so that we can directly get expected data type without type cast the values

Example:

If our expected Data type is double


Form Input Element

<input type="text" name="<portlet:namespace/>examFee" id="<portlet:namespace/>examFee"/>

Get the value in Action Method

double examFee=ParamUtil.getDouble(actionRequest,"examFee");


Similarly we have different data type returning methods so that it is very convenient way to get the data as we expected data type.

Example Available Methods:


Access Multiple Values

Some time user may select multiple options or we can say user may check multiple check boxes.

ParamUtil have method i.e. ParamUtil.getParameterValues(---) it will capture array of string values for specific form input element and generally it is checkboxes with same “name” attribute or multiple option selected combo box.

Syntax:


ParamUtil.getParameterValues(actionRequest,"inputName",defaultValue);


Scenario:

Assume scenario Student may obtained multiple subjects


Form Input Check Box Element

<b>Subjects Obtained</b><br/>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Maths">Maths<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Physics">Physics<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Chemistry">Chemistry<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Bio Technology">Biotechnology<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Computer Science">Computer Science<br>

Get the Multiple values for Single Input in Action Method

String[] subjects = ParamUtil.getParameterValues(actionRequest,"subjects",null);


Note:

When we observe check box names are same for everyone and this is called same element “name” attribute carrying multiple values.

Display Submitted Data in other JSP Page.

We already aware of form submitted to Portlet Action Method and we capture d the data in the above steps. Now we will send captured form data to JSP page from portlet class action method.
We will use set Attribute method to pass data from Action Method to JSP page.

Before send data to JSP page first we need to prepare data as some specific objet format so that we can pass object through set Attribute method

Scenario:

We already get the all student data through form submission and now we will use map object to prepare all student details.

Example:

In Action Method


String firstName=ParamUtil.getString(actionRequest,"firstName");
String lastName=ParamUtil.getString(actionRequest,"lastName");
double examFee=ParamUtil.getDouble(actionRequest,"examFee",00.00);
String sex=ParamUtil.getString(actionRequest,"sex");
String[] subjects = ParamUtil.getParameterValues(actionRequest,"subjects",null);
String acadamicYear=ParamUtil.getString(actionRequest,"acadamicYear");
String address=ParamUtil.getString(actionRequest,"address");
//Perepare Map object to send date to JSP Page to display
Map<String,String> studentMapObject=new HashMap<String,String>();
studentMapObject.put("firstName", firstName);
studentMapObject.put("lastName", lastName);
studentMapObject.put("examFee", String.valueOf(examFee));
studentMapObject.put("sex", sex);
studentMapObject.put("acadamicYear",acadamicYear);
studentMapObject.put("address",address);

//Send Map object to JSP page we wil use setAttribute(--) method on request object
actionRequest.setAttribute("studentMapObject", studentMapObject);


JSP Page:


<%
Map<String,String> studentMap=(Map<String,String>)renderRequest.getAttribute("studentMapObject");
if(studentMap!=null){
%>
<b>First Name: </b><%=studentMap.get("firstName")%>    <br/>
<b>Last Name:</b>  <%=studentMap.get("lastName")%><br/>
<b>Exam Fee: </b> <%=studentMap.get("examFee")%><br/>
<b>Gender: </b> <%=studentMap.get("sex")%><br/>
<b>Acadamic Year: </b> <%=studentMap.get("acadamicYear")%><br/>
<b>Address:  </b><%=studentMap.get("address")%><br/>
<b>Subjects Obtained:</b><br/>
<%}%>


Now we have done all the steps with respect to form submission and display data in other JSP page.

Navigate to other JSP page from Action Method

We will use following code to navigate other JSP page from action method.


actionResponse.setRenderParameter("mvcPath","/html/jsps/display_student.jsp");


Success/Error Messages

Generally when process some action we need to display success or error message based on result and it will be displayed in JSP page.

Add Success Message in Portlet Action Method


SessionMessages.add(actionRequest.getPortletSession(),"student-form-success");


Display Success Message in JSP Page


<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

<% if(SessionMessages.contains(renderRequest.getPortletSession(),"student-form-success")){%>
<liferay-ui:success key="student-form-success" message="Student form Submitted successfully and following are the details." />
<%} %>


Note:

We have used liferay UI tag library so we need add tag lib URI in jsp page.

SessionMessages class has many methods and you can have look into those methods.

Add Error Message in Portlet Action Method


SessionErrors.add(actionRequest.getPortletSession(),"student-form-error");


Display Error Message in JSP Page


<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

<% if(SessionErrors.contains(renderRequest.getPortletSession(),"student-form-error")){%>
<liferay-ui:error key="student-form-error" message="Student form Submitted have problem Please try again." />
<%} %>


Note:

We have sued liferay UI tag library so we need add tag lib URI in jsp page.

SessionErrors class has many methods you can have look into those methods.

Complete Example of Student Liferay MVC Portlet

Portlet Action Class and Action Method


package com.meera.liferaymvc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ListUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class StudentMVCPortletAction extends MVCPortlet {
       public void addStudent(ActionRequest actionRequest,
                     ActionResponse actionResponse) throws IOException, PortletException {
              try{
              String firstName = ParamUtil.getString(actionRequest, "firstName");
              String lastName = ParamUtil.getString(actionRequest, "lastName");
              double examFee = ParamUtil.getDouble(actionRequest, "examFee", 00.00);
              String sex = ParamUtil.getString(actionRequest, "sex");
              String[] subjects = ParamUtil.getParameterValues(actionRequest,
                           "subjects", null);
              String acadamicYear = ParamUtil
                           .getString(actionRequest, "acadamicYear");
              String address = ParamUtil.getString(actionRequest, "address");
              // Perepare Map object to send date to JSP Page to display
              Map<String, String> studentMapObject = new HashMap<String, String>();
              studentMapObject.put("firstName", firstName);
              studentMapObject.put("lastName", lastName);
              studentMapObject.put("examFee", String.valueOf(examFee));
              studentMapObject.put("sex", sex);
              studentMapObject.put("acadamicYear", acadamicYear);
              studentMapObject.put("address", address);
              // Send Map object to JSP page we wil use setAttribute(--) method on
              // request object
              actionRequest.setAttribute("studentMapObject", studentMapObject);
              // We have multiple subjects so we will send it seperate request
              // attribute
              List<String> subjectsList = new ArrayList<String>();
              // for flexible manipulation we will convert noram array i.e subject
              // array to List
              subjectsList = ListUtil.toList(subjects);
              actionRequest.setAttribute("subjectsList", subjectsList);
              // we will display all student information in display_student.jsp so we
              // will use setRenderParameter method on response object
              // addding success message
              SessionMessages.add(actionRequest.getPortletSession(),
                           "student-form-success");
              actionResponse.setRenderParameter("mvcPath",
                           "/html/jsps/display_student.jsp");
              }catch(Exception e){
                     SessionErrors.add(actionRequest.getPortletSession(),"student-form-error");
                     e.printStackTrace();
                    
              }
       }

}


Student Form JSP Page


<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL var="addStudentActionURL" windowState="normal" name="addStudent">
</portlet:actionURL>
<h2>Student Form</h2>
<form action="<%=addStudentActionURL%>" name="studentForm"  method="POST">
<b>First Name</b><br/>
<input  type="text" name="<portlet:namespace/>firstName" id="<portlet:namespace/>firstName"/><br/>
<b>Last Name</b><br/>
<input type="text" name="<portlet:namespace/>lastName" id="<portlet:namespace/>lastName"/><br/>
<b>Exam Fee</b><br/>
<input type="text" name="<portlet:namespace/>examFee" id="<portlet:namespace/>examFee"/><br/>
<b>Gender</b><br/>
<input type="radio" name="<portlet:namespace/>sex" value="male">Male<br>
<input type="radio" name="<portlet:namespace/>sex" value="female">Female<br/>
<b>Subjects Obtained</b><br/>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Maths">Maths<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Physics">Physics<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Chemistry">Chemistry<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Bio Technology">Biotechnology<br>
<input type="checkbox" name="<portlet:namespace/>subjects" value="Computer Science">Computer Science<br>
<b>Academic Year</b><br>
<select name="<portlet:namespace/>acadamicYear">
  <option value="I Year">I Year</option>
  <option value="II Year">II Year</option>
  <option value="III Year">III Year</option>
  <option value="IV Year">IV Year</option>
</select><br>
<b>Address</b><br/>
<textarea rows="4" cols="50" name="<portlet:namespace/>address">
</textarea><br/>
<input type="submit" name="addStudent" id="addStudent" value="Add Student"/>
</form>


Display Student Details JSP page.

<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<portlet:defineObjects />
<portlet:renderURL var="addStundentRenderURL" windowState="normal">
</portlet:renderURL>
<h2>Display Student Details</h2><br/>
<a href="<%=addStundentRenderURL.toString()%>">Add Student</a><br/>
<% if(SessionMessages.contains(renderRequest.getPortletSession(),"student-form-success")){%>
<liferay-ui:success key="student-form-success" message="Student form Submitted successfully and following are the details." />
<%} %>

<% if(SessionErrors.contains(renderRequest.getPortletSession(),"student-form-error")){%>
<liferay-ui:error key="student-form-error" message="Student form Submitted have problem Please try again." />
<%} %>
<%
Map<String,String> studentMap=(Map<String,String>)renderRequest.getAttribute("studentMapObject");
if(studentMap!=null){
%>
<b>First Name: </b><%=studentMap.get("firstName")%>    <br/>
<b>Last Name:</b>  <%=studentMap.get("lastName")%><br/>
<b>Exam Fee: </b> <%=studentMap.get("examFee")%><br/>
<b>Gender: </b> <%=studentMap.get("sex")%><br/>
<b>Acadamic Year: </b> <%=studentMap.get("acadamicYear")%><br/>
<b>Address:  </b><%=studentMap.get("address")%><br/>
<b>Subjects Obtained:</b><br/>
<%}%>
<%
List<String> subjectsList=(List<String>)renderRequest.getAttribute("subjectsList");
if(subjectsList!=null){
for(String subject:subjectsList){
%>
<%=subject%><br/>
<%}}%>


Portlet Screens:

Screen: 1


Screen: 2



Portlet Download Link


Note:

In the above example I just used simple html tags and normal code in entire portlet development. 

In future article we will use AUI tags and AUI java script to develop same portlet.


Author

1 comment :


  1. Pretty component to content. I just stumbled upon your web site and in accession capital to assert that I get
    actually enjoyed account your weblog posts. Any way
    I’ll be subscribing to your augment or even I achievement you get right of entry to constantly
    rapidly.대구오피

    ReplyDelete

Recent Posts

Recent Posts Widget

Popular Posts