Monday, May 26, 2014

Liferay MVC Portlet Database Interactions / Liferay MVC CRUD Operations

Introduction:

Liferay MVC is portlet frame work given by Liferay and it is specific to liferay environment.
We already well aware of Liferay MVC frame work from Liferay Savvy previous articles.




Environment:

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

Note:

Please go through above three articles then you will be much aware of Liferay MVC framework and its use in portlet development.

Now we will see how liferay portlet interact with database to store the data and fetch the data from database.

Database interaction is like Insert, Delete, Read and Update the data in database.
We already know there are many technologies in Java that is java applications connect to database and do CRUD operations.

When we are talking about Database interaction in java application then we have a technology called JDBC. Similarly if we go little bit advanced concept then Hibernate comes into picture.

Liferay also have used JDBC and Hibernate concepts to interact with database and it will perform CRUD operations.

But we never write any legacy JDBC java code or Hibernate code when we work with database interactions and all the code already abstracted and we will use simple Util classes and its methods to perform operations.

Liferay implemented many classes and interfaces so that we can develop database interaction portlet pretty easy.

We have two ways to connect to database in Liferay
  1. Legacy JDBC Code
  2. Liferay Service Builder

Legacy JDBC Code

Liferay have implemented some classes and it use simple JDBC code to interact with database.
These classes are available in Liferay Kernel level so that we can use anywhere in Plugin portlet development.

We have class called DataAccess so that we can use this class to get the Connection object once we get the connection reaming all are like simple JDBC code to connect to database and perform operations.

The following is simple code using Data Access Class


import java.io.IOException;
import java.sql.SQLException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import com.liferay.portal.kernel.dao.jdbc.DataAccess;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class StudentMVCPortletAction extends MVCPortlet {
       public void getStudent(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException,
PortletException, SQLException {
java.sql.Connection con = null;
java.sql.Statement st = null;
try {
con = DataAccess.getConnection();
st = con.createStatement();
java.sql.ResultSet rs = st.executeQuery("SELECT * FROM Student");
while (rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
System.out.println("Student FirstName:" + firstName);
System.out.println("Student Last Name:" + lastName);
}
} catch (Exception e) {
} finally {
st.close();
con.close();
}
}
}


Note:

This is very Legacy JDBC code and we won’t use in real portlet development. We will use above method in some of specific scenarios.

Liferay Service Builder

Liferay Service Builder is tool to generate database interaction layer/service layer to the portlet.

Service layer consist of set of classes and interfaces so that we can use these classes to interact with database and perform database operation in portlet.

Service Builder tool help us to generate service layer so that developer need not worry about persistence code and need to concentrate on business logic.

Generally in the application development we need database service layer and the operations we used in persistence layer is common i.e. CRUD operations.

Instead writing same CRUD operation persistence logic for multiple times we have a tool in Liferay so that it will be generated all classes and interfaces and developer need not to worry about persistence logic he/she can concentrate only on writing business logic.

Liferay Service Builder is simple ANT script when we run ant target then all classes and interfaces will be created.

When we create Liferay MVC Portlet using Plugins SDK then portlet consists of ANT build file and the build file have service builder related target by default.

Liferay Service Builder used Spring Hibernate DAO implementation to create the services.

After successfully run service builder we can see many configuration files and java implementation classes all are following spring hibernate DAO implementation mechanism.

More details about Liferay Service Builder follow the article


The following are the steps to Generate Service Layer in Portlet.
  1. Create simple Liferay MVC portlet using Liferay IDE in eclipse
  2. Create Service.xml file in Portlet WEB-INF directory
  3. Define required entities/tables in service.xml
  4. Run the Service builder
  5. Using Generated Database services In Portlet Development

Create simple Liferay MVC portlet using Liferay IDE in eclipse

Firs we need to create simple Liferay MVC portlet using Liferay IDE in eclipse. This is very simple to create in eclipse.

Go through below article to create simple Liferay MVC Portlet


Create Service.xml file in Portlet WEB-INF directory

Now we need to create service.xml file in portlet WEB-INF directory. This is the configuration file to service builder tool and Service Builder use configuration file to generate required services (classes, interfaces) to portlet and these services provided the database interactions from the portlet.

The following screen shows service.xml file in portlet WEB-INF directory


Note:

In eclipse with Liferay IDE we have option to create service.xml with sample entity using GUI interface.

We can also create manually in the above specified location or we can use Liferay IDE to create service.xml file.

Define required entities/tables in service.xml

Now we need to defined required entities in service.xml file so that service builder will generate services for defined entities/tables.

service.xml consist of  defined tags from which we will define the entities. Tags information is available in service builder DTD file.

When we define entity we need to specify primary key column, column data type, column name and other required things. All the tags information is based on its DTD.

The following is service builder DTD we can get more information about service builder tags for service.xml



Assume we have an entity/table Student

The following is service.xml entity configuration


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.2.0//EN"
"http://www.liferay.com/dtd/liferay-service-builder_6_2_0.dtd">
<service-builder package-path="com.meera.dbservice">
       <author>LiferaySavvy</author>
       <namespace>LS</namespace>
       <entity name="Student" local-service="true" remote-service="true">
              <!-- PK fields -->
              <column name="studentId" type="long" primary="true" />
              <column name="firstName" type="String" />
              <column name="lastName" type="String" />
              <column name="studentAge" type="int" />
              <column name="studentGender" type="int" />
              <column name="studentAddress" type="String" />
              <!-- Order -->
              <order by="asc">
                     <order-column name="studentId" />
              </order>
              <!-- Finder methods -->
              <finder name="byGender" return-type="Collection">
                     <finder-column name="studentGender"/>
              </finder>
       </entity>
</service-builder>


Run the Service builder

Once we completed the configuration now we need run service builder. We can run the service builder in eclipse from ANT view. We need to click on build-service target from the ANT view
In normal ant command for run service builder as follows


ant build-service


The following is ANT build-service in eclipse ant view



The following is screen to show build success


Once we run service builder it will generate many classes and interfaces. All interfaces will be packages as jar file and it will be available in WEB-INF/lib directory.

It will also generate the required SQL script and it will be executed when we deploy the portlet so that required tables and indexes will be created in database. You can see the script in sql (docroot\WEB-INF\sql) directory of portlet.

The table name which is creates in database will be service builder namespace_entity name which we have given in service.xml

In the above example the table the name in database is LS_Student

The following screen shows services after run service builder



Using Generated Database services in Portlet Development

Once we generated the services then we can use in portlet development

We already know we have used Student entity in service.xml so that we will get many services related to Student entity/table. We will use Util classes to interact with database.

It will generate many classes and interfaces but we will use only Util java classes in portlet development.

The following are main java Util classes


XXXServiceUtil
XXXLocalServiceUtil
XXXUtil

XXX is entity name which we have given in service.xml and our example its Student

StudetLocalServiceUtil
StudentServiceUtil
StudentUtil


Mostly we will use Util class’s related methods to perform database CRUD operations.
  1. Add /Create record
  2. Delete Record
  3. Update Record
  4. Show Data/Record

Add /Create record  

When we create or add record to the table first we need create persistence object and need to fill the data in object then finally add to the table using XXXLocalServiceUtil.addXXX() method.When we create persistence object we need a primary key so we will use CounterLocalServiceUtil.increment() to create unique id for the record.

The following is code snippet to add record to the table.

Type: 1


//create primary key
long studentId=CounterLocalServiceUtil.increment();
//create student persistance object
Student student=null;
student=StudentLocalServiceUtil.createStudent(studentId);
//fill the data in persistance object
student.setFirstName(firstName);
student.setLastName(lastName);
student.setStudentAge(studentAge);
student.setStudentGender(studentGender);
student.setStudentAddress(address);
//Add student persistance object to database student table
student=StudentLocalServiceUtil.addStudent(student);


Note:

In the above code we are creating primary key using Counter Service.

Type: 2


Student student=null;
student=new StudentImpl();
//fill the data in persistance object
student.setFirstName(firstName);
student.setLastName(lastName);
student.setStudentAge(studentAge);
student.setStudentGender(studentGender);
student.setStudentAddress(address);
//Add student persistance object to database student table
student=StudentLocalServiceUtil.addStudent(student);


Note:

In the above code we are creating persistence object with new operator so primary key will be auto generated.

In the both cases it will return student object if the record added successfully otherwise it will return null value.

Update Record

To update record first we need to get existed record with primary and need to fill new updated information in persistence object then we will update record.

The following is code snippet to update record.


Student student=StudentLocalServiceUtil.getStudent(studentId);
//fill update information
student.setFirstName(firstName);
student.setLastName(lastName);
student.setStudentAge(studentAge);
student.setStudentGender(studentGender);
student.setStudentAddress(address);
student=StudentLocalServiceUtil.updateStudent(student);


Note:

Once data is updated it will return updated persistence object.

Delete Record

We need primary key to delete the record.

The following is code for delete record


long studentId = ParamUtil.getLong(actionRequest,"studentId");

Student student=StudentLocalServiceUtil.deleteStudent(studentId);


We can also delete record by object


Student student=StudentLocalServiceUtil.getStudent(studentId);

student=StudentLocalServiceUtil.deleteStudent(student);


Note:

Once record is deleted it will return deleted persistence object.

Show Data/Record

We have different methods to get the records we can get single record by primary key and we can fetch all records too.

We can also fetch the record by using columns based these methods are available in XXXUtil methods. We have many finder methods and all finder methods will be available in XXXUtil class.

To create any finder methods on required columns then we need to add configuration in service.xml file so that finder methods will be created to specific columns.

The following is simple tag which will generate finder method and it fetch the record based on given column


<entity name="Student" local-service="true" remote-service="true">
              <!-- PK field -->
              <column name="studentId" type="long" primary="true" />
              <column name="firstName" type="String" />
              <column name="lastName" type="String" />
              <column name="studentAge" type="int" />
              <column name="studentGender" type="int" />
              <column name="studentAddress" type="String" />
             
              <!-- Finder methods -->
              <finder name="byGender" return-type="Collection">
                     <finder-column name="studentGender"/>
              </finder>
       </entity>

Note:

We will see more about finder methods in future articles.

The following are code snippets to fetch records.

Get Record by Primary Key


Student student=StudentLocalServiceUtil.getStudent(studentId);


Get all records


List<Student> studentList=
StudentLocalServiceUtil.getStudents(0,
StudentLocalServiceUtil.getStudentsCount());


The following are the available methods in StudentLocalService.java interface


public com.meera.dbservice.model.Student addStudent(
              com.meera.dbservice.model.Student student)
              throws com.liferay.portal.kernel.exception.SystemException;
      

public com.meera.dbservice.model.Student createStudent(long studentId);


public com.meera.dbservice.model.Student deleteStudent(
              com.meera.dbservice.model.Student student)
              throws com.liferay.portal.kernel.exception.SystemException;


public java.util.List dynamicQuery(
              com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
              throws com.liferay.portal.kernel.exception.SystemException;


public long dynamicQueryCount(
              com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery)
              throws com.liferay.portal.kernel.exception.SystemException;

public java.util.List<com.meera.dbservice.model.Student> getStudents(
              int start, int end)
              throws com.liferay.portal.kernel.exception.SystemException;

public int getStudentsCount()
              throws com.liferay.portal.kernel.exception.SystemException;

public com.meera.dbservice.model.Student updateStudent(
              com.meera.dbservice.model.Student student)
              throws com.liferay.portal.kernel.exception.SystemException;

public com.meera.dbservice.model.Student deleteStudent(long studentId)
              throws com.liferay.portal.kernel.exception.PortalException,
                     com.liferay.portal.kernel.exception.SystemException;

public com.meera.dbservice.model.Student addStudent(
              com.meera.dbservice.model.Student student)
              throws com.liferay.portal.kernel.exception.SystemException;


public com.meera.dbservice.model.Student createStudent(long studentId);



Important Points
  • Service Builder is tool to generate database interaction layer to the portlet.
  • Service Builder is simple ANT script and it has target to run the tool.
  • Service Builder ANT target is available in portlet build.xml file by default so we can run target to generate service layer for portlet.
  • Service Builder need service.xml file so that it will use those configuration to generate services.
  • Service.xml file consist of set of predefined tags and it will be available in Service Builder DTD file.
  • Service builder use the Spring Hibernate DAO implementation concept to generate services.
  • Service Builder tool generate all java interfaces, implementation classes and spring hibernate configuration files, apart from these it will also generated required SQL scripts.
  • SQL script will be run at time of portlet deployment it’s generally created table scripts and indexes scripts.
  • For each modification in service.xml file or any other changes in service layer related classes we need to re run the service builder.
  • ant build-service is target to run service builder.
  • Service Builder packages all interfaces and required Util classes as porletName-portlet.jar file.
  • Services jar file will be used in other portlet to obtain other portlet services. This is called sharing of services in other portlet.

Note:

There are many things behind Liferay Service Builder we will see more details in coming articles.

Download Portlet


Portlet Screens:

Default View



Add student


Update student



Delete Student


Display Student



Complete Code of Student Liferay MVC Service Builder Portlet

Portlet Action Class (StudentMVCPortletAction.java)


package com.meera.liferaymvc;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.meera.dbservice.model.Student;
import com.meera.dbservice.model.impl.StudentImpl;
import com.meera.dbservice.service.StudentLocalServiceUtil;
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");
int studentAge = ParamUtil.getInteger(actionRequest, "studentAge");
int studentGender = ParamUtil.getInteger(actionRequest, "sex", 1);
String address = ParamUtil.getString(actionRequest, "address");
// add student record
// create primary key
long studentId = CounterLocalServiceUtil.increment();
// create student persistance object
Student student = null;
student = new StudentImpl();
student = StudentLocalServiceUtil.createStudent(studentId);
// fill the data in persistance object
student.setFirstName(firstName);
student.setLastName(lastName);
student.setStudentAge(studentAge);
student.setStudentGender(studentGender);
student.setStudentAddress(address);
// Add student persistance object to database student table
student = StudentLocalServiceUtil.addStudent(student);
if (student != null) {
// adding success message
SessionMessages.add(actionRequest.getPortletSession(),
"student-add-success");
_log.info("Student have been added successfylly");
} else {
SessionErrors.add(actionRequest.getPortletSession(),
"student-add-error");
_log.error("There is an Erron in adding Student");
}
// navigate to add student jsp page
actionResponse.setRenderParameter("mvcPath",
"/html/jsps/add_student.jsp");
} catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),
"student-add-error");
e.printStackTrace();
}
}

public void deleteStudent(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
try {
long studentId = ParamUtil.getLong(actionRequest, "studentId");
Student student = StudentLocalServiceUtil.deleteStudent(studentId);
if (student != null) {
// adding success message
SessionMessages.add(actionRequest.getPortletSession(),
"student-delete-success");
_log.info("Student have been deleted successfylly");
} else {
SessionErrors.add(actionRequest.getPortletSession(),
"student-delete-error");
_log.error("There is an Erron in delete Student");
}
// navigate to add student jsp page
actionResponse.setRenderParameter("mvcPath",
"/html/jsps/delete_student.jsp");
} catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),
"student-add-error");
e.printStackTrace();
}
}

public void updateStudent(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
try {
long studentId = ParamUtil.getLong(actionRequest, "studentId");
String firstName = ParamUtil.getString(actionRequest, "firstName");
String lastName = ParamUtil.getString(actionRequest, "lastName");
int studentAge = ParamUtil.getInteger(actionRequest, "studentAge");
int studentGender = ParamUtil.getInteger(actionRequest, "sex", 1);
String address = ParamUtil.getString(actionRequest, "address");
Student student = StudentLocalServiceUtil.getStudent(studentId);
if (student != null) {
// fill update information
student.setFirstName(firstName);
student.setLastName(lastName);
student.setStudentAge(studentAge);
student.setStudentGender(studentGender);
student.setStudentAddress(address);
student = StudentLocalServiceUtil.updateStudent(student);
if (student != null) {
// adding success message
SessionMessages.add(actionRequest.getPortletSession(),
"student-update-success");
_log.info("Student have been updated successfylly");
} else {
SessionErrors.add(actionRequest.getPortletSession(),
"student-update-error");
_log.error("There is an Erron in delete Student");
}
} else {
SessionErrors.add(actionRequest.getPortletSession(),
"student-update-error");
_log.error("Could not find student.");
}
// navigate to add student jsp page
actionResponse.setRenderParameter("mvcPath",
"/html/jsps/update_student.jsp");
} catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),
"student-update-error");
e.printStackTrace();
}
}

public void getStudent(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
try {
long studentId = ParamUtil.getLong(actionRequest, "studentId");
String cmd = ParamUtil.getString(actionRequest, "cmd");
Student student = StudentLocalServiceUtil.getStudent(studentId);
if (student != null) {
// adding success message
actionRequest.setAttribute("studentObject", student);
_log.info("Student have been found for specific primary key successfylly");
} else {
_log.error("Stundet not found");
}
if (cmd.equals("DELETE")) {
// navigate to add student jsp page
actionResponse.setRenderParameter("mvcPath",
"/html/jsps/delete_student.jsp");
}
if (cmd.equals("UPDATE")) {
// navigate to add student jsp page
actionResponse.setRenderParameter("mvcPath",
"/html/jsps/update_student.jsp");
}
if (cmd.equals("VIEW")) {
// navigate to add student jsp page
actionResponse.setRenderParameter("mvcPath",
"/html/jsps/display_student.jsp");
}

} catch (Exception e) {
SessionErrors.add(actionRequest.getPortletSession(),
"student-add-error");
e.printStackTrace();
}
}

private static Log _log = LogFactoryUtil
.getLog(StudentMVCPortletAction.class);
}


Default View JSP Page (/html/jsps/view.jsp)


<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<liferay-theme:defineObjects />
<h1>Liferay Service Builder/ Student CRUD Operations</h1>
<portlet:renderURL var="addStudent">
<portlet:param name="mvcPath" value="/html/jsps/add_student.jsp"/>
</portlet:renderURL>
<portlet:renderURL var="updateStudent">
<portlet:param name="mvcPath" value="/html/jsps/update_student.jsp"/>
</portlet:renderURL>
<portlet:renderURL var="dislayStudent">
<portlet:param name="mvcPath" value="/html/jsps/display_student.jsp"/>
</portlet:renderURL>
<portlet:renderURL var="deleteStudent">
<portlet:param name="mvcPath" value="/html/jsps/delete_student.jsp"/>
</portlet:renderURL>
<br/>
<a href="<%=addStudent.toString()%>">Add Student</a><br/>
<a href="<%=updateStudent.toString()%>">Update Student</a><br/>
<a href="<%=deleteStudent.toString()%>">Delete Student</a><br/>
<a href="<%=dislayStudent.toString()%>">Display Student</a><br/>


Add Student JSP Page (/html/jsps/add_student.jsp)


<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL var="homeURL"></portlet:renderURL>
<portlet:actionURL var="addStudentActionURL" windowState="normal" 
name="addStudent">
</portlet:actionURL>
<% if(SessionMessages.contains(renderRequest.
getPortletSession(),"student-add-success")){%>
<liferay-ui:success key="student-add-success" message="Student information
have been added successfully." />
<%} %>
<% if(SessionErrors.contains(renderRequest.getPortletSession(),
"student-add-error")){%>
<liferay-ui:error key="student-add-error" message="There is an 
Error occured while adding student please try again" />
<%} %>
<h2>Add Student</h2>
<a href="<%=homeURL.toString() %>">Home</a><br/><br/>
<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>Age</b><br/>
<input type="text" name="<portlet:namespace/>studentAge" id="<portlet:namespace/>studentAge"/><br/>
<b>Gender</b><br/>
<input type="radio" name="<portlet:namespace/>sex" value="1">Male<br>
<input type="radio" name="<portlet:namespace/>sex" value="0">Female<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>


Update Student JSP Page (/html/jsps/update_student.jsp)


<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@page import="com.meera.dbservice.service.StudentLocalServiceUtil"%>
<%@page import="java.util.List"%>
<%@page import="com.meera.dbservice.model.Student"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL var="homeURL"></portlet:renderURL>
<portlet:actionURL var="updateStudentActionURL" windowState="normal" 
name="updateStudent">
</portlet:actionURL>
<portlet:actionURL var="getStudentActionURL" windowState="normal" name="getStudent">
<portlet:param name="cmd" value="UPDATE"/>
</portlet:actionURL>
<h2>Update Student</h2>
<a href="<%=homeURL.toString() %>">Home</a><br/><br/>
<% if(SessionMessages.contains(renderRequest.getPortletSession(),"student-update-success")){%>
<liferay-ui:success key="student-update-success" message="Selected Student
 information have been updated successfully." />
<%} %>
<% if(SessionErrors.contains(renderRequest.getPortletSession(),
"student-update-error")){%>
<liferay-ui:error key="student-update-error" message="There is an 
Error occurred while updating student please try again" />
<%} %>
<%
List<Student> studentList=StudentLocalServiceUtil.
getStudents(0,StudentLocalServiceUtil.getStudentsCount());
Student selecteStudentObject=(Student)renderRequest.getAttribute("studentObject");
%>
<form action="<%=getStudentActionURL.toString()%>" name="studentForm"  method="POST">
<b>Select Student ID</b><br>
<select name="<portlet:namespace/>studentId" onchange="submitform(this.value);">
<option value="-1">--select--</option>
<%for(Student student:studentList){%>
  <option 
value="<%=student.getStudentId()%>" <%=selecteStudentObject!=null&&selecteStudentObject.getStudentId()==
student.getStudentId()?"selected":""%>>
<%=student.getStudentId()%></option>
  <%} %>
</select><br>
<%if(selecteStudentObject!=null){%>
<b>First Name</b><br/>
<input  type="text" name="<portlet:namespace/>firstName"
id="<portlet:namespace/>firstName" 
value="<%=selecteStudentObject.getFirstName()%>"/><br/>
<b>Last Name</b><br/>
<input type="text" name="<portlet:namespace/>lastName" 
id="<portlet:namespace/>lastName" 
value="<%=selecteStudentObject.getLastName()%>"/><br/>
<b>Age</b><br/>
<input type="text" name="<portlet:namespace/>studentAge" 
id="<portlet:namespace/>studentAge" 
value="<%=selecteStudentObject.getStudentAge()%>"/><br/>
<b>Gender</b><br/>
<input type="radio" name="<portlet:namespace/>sex"
value="1" <%=selecteStudentObject.getStudentGender()==1?"checked":""%>>Male<br>
<input type="radio" name="<portlet:namespace/>sex"
value="0" <%=selecteStudentObject.getStudentGender()==0?"checked":""%>>Female<br/>
<b>Address</b><br/>
<textarea rows="4" cols="50" name="<portlet:namespace/>address">
<%=selecteStudentObject.getStudentAddress()%>
</textarea><br/>
<input type="button" name="updateStudent" id="updateStudent" 
value="Update Student" onclick="updateStudentRecord();"/>
<%}%>
</form>
<script>
function submitform(selectedValue)
{
  if(selectedValue!="-1"){
         document.studentForm.submit(); 
  }
      
}
function updateStudentRecord()
{
       document.studentForm.action="<%=updateStudentActionURL.toString()%>"
    document.studentForm.submit();
}
</script>


Delete Student JSP Page (/html/jsps/delete_student.jsp)


<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@page import="com.meera.dbservice.service.StudentLocalServiceUtil"%>
<%@page import="java.util.List"%>
<%@page import="com.meera.dbservice.model.Student"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL var="homeURL"></portlet:renderURL>
<portlet:actionURL var="deleteStudentActionURL" windowState="normal" 
name="deleteStudent">
</portlet:actionURL>
<portlet:actionURL var="getStudentActionURL" windowState="normal" 
name="getStudent">
<portlet:param name="cmd" value="DELETE"/>
</portlet:actionURL>
<h2>Delete Student</h2>
<a href="<%=homeURL.toString() %>">Home</a><br/><br/>
<% if(SessionMessages.contains(renderRequest.
getPortletSession(),"student-delete-success")){%>
<liferay-ui:success key="student-delete-success" message="Selected Student 
information have been deleted successfully." />
<%} %>
<% if(SessionErrors.contains(renderRequest.getPortletSession(),
"student-delete-error")){%>
<liferay-ui:error key="student-delete-error" message="There is an Error occured 
while deleting student please try again" />
<%} %>
<%
List<Student> studentList=StudentLocalServiceUtil.
getStudents(0,StudentLocalServiceUtil.getStudentsCount());
Student selecteStudentObject=(Student)renderRequest.getAttribute("studentObject");
%>
<form action="<%=getStudentActionURL.toString()%>" name="studentForm"  method="POST">
<b>Select Student ID</b><br>
<select name="<portlet:namespace/>studentId" onchange="submitform(this.value);">
<option value="-1">--select--</option>
<%for(Student student:studentList){%>
<option 
value="<%=student.getStudentId()%>" <%=selecteStudentObject!=null&&selecteStudentObject.getStudentId()==
student.getStudentId()?"selected":""%>>
<%=student.getStudentId()%></option>
  <%} %>
</select><br>
<%if(selecteStudentObject!=null){%>
Student Name:
<%=selecteStudentObject.getFirstName()+"&nbsp;"+
selecteStudentObject.getLastName()%>
<br/>
Student Age: <%=selecteStudentObject.getStudentAge() %><br/>
Student Gender: <%=selecteStudentObject.getStudentGender()==1?"Male":"Famale"%>
<br/>
Address: <%=selecteStudentObject.getStudentAddress()%><br/>
<input type="button" name="deleteStudent" id="addStudent" value="Delete
 Student" onclick="deleteStudentRecord();"/>
<%}%>
</form>
<script>
function submitform(selectedValue)
{
  if(selectedValue!="-1"){
         document.studentForm.submit(); 
  }
      
}
function deleteStudentRecord()
{
       document.studentForm.action="<%=deleteStudentActionURL.toString()%>"
    document.studentForm.submit();
}
</script>


Display Student JSP Page (/html/jsps/display_student.jsp)


<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@page import="com.meera.dbservice.service.StudentLocalServiceUtil"%>
<%@page import="java.util.List"%>
<%@page import="com.meera.dbservice.model.Student"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionErrors"%>
<%@page import="com.liferay.portal.kernel.servlet.SessionMessages"%>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL var="homeURL"></portlet:renderURL>
<portlet:actionURL var="getStudentActionURL" windowState="normal" name="getStudent">
<portlet:param name="cmd" value="VIEW"/>
</portlet:actionURL>
<h2>Display Student Information</h2>
<a href="<%=homeURL.toString() %>">Home</a><br/><br/>
<%
List<Student> studentList=StudentLocalServiceUtil.
getStudents(0,StudentLocalServiceUtil.getStudentsCount());
Student selecteStudentObject=(Student)renderRequest.getAttribute("studentObject");
%>
<form action="<%=getStudentActionURL.toString()%>" name="studentForm"  method="POST">
<b>Select Student ID</b><br>
<select name="<portlet:namespace/>studentId" onchange="submitform(this.value);">
<option value="-1">--select--</option>
<%for(Student student:studentList){%>
<option 
value="<%=student.getStudentId()%>" <%=selecteStudentObject!=null&&selecteStudentObject.getStudentId()==
student.getStudentId()?"selected":""%>>
<%=student.getStudentId()%></option>
  <%} %>
</select><br>
<%if(selecteStudentObject!=null){%>
<h3>The following are the selected Student Information</h3><br/>
Student Name:
<%=selecteStudentObject.getFirstName()+"&nbsp;"
+selecteStudentObject.getLastName()%><br/>
Student Age: <%=selecteStudentObject.getStudentAge() %><br/>
Student Gender: <%=selecteStudentObject.getStudentGender()==1?"Male":"Famale"%><br/>
Address: <%=selecteStudentObject.getStudentAddress()%><br/>
<%}%>
</form>
<script>
function submitform(selectedValue)
{
  if(selectedValue!="-1"){
         document.studentForm.submit(); 
  }
      
}
</script>


Related Articles







Author

1 comment :

Recent Posts

Recent Posts Widget

Popular Posts