The goal of this post is to add Database interaction to the Struts Portlet.
Steps Involved:
1. Create Folder structure in ext-impl and ext-web
2. Create your table structure in service.xml
3. Generate Service and Persistence Layer Classes with Ant’s Build-Service
4. Copy auto-generated MySQL table into database.
5. Create the Struts Action Portlet
6. Update Service Layer Files
7. JSP / Java action file updation.
1. Folder Structure:
Java Fiels >>>>>>> ext-impl/src/com/testing/portlet/company
Jsp Files >>>>>>> ext-web/docroot/html/testing/company
2. Service.xml
(create this file under “/ext/ext-impl/src/com/testing/portlet/company“)
<?xml version=”1.0″?>
<!DOCTYPE service-builder PUBLIC “-//Liferay//DTD Service Builder 5.2.0//EN” “http://www.liferay.com/dtd/liferay-service-builder_5_2_0.dtd”>
<service-builder package-path=”com.testing.portlet.company”>
<namespace>MyCompany</namespace>
<entity name=”MyCompany” local-service=”true” remote-service=”true” table=”my_company”>
<column name=”companyId” type=”long” primary=”true” />
<!– basic Info –>
<column name=”companyName” type=”String” />
<column name=”address” type=”String” />
<column name=”startDate” type=”Date” />
<column name=”annualIncome” type=”float” />
<column name=”stockQty” type=”double” />
<column name=”active” type=”int” />
<!– Finder Method for companyName Info –>
<finder name=”Name” return-type=”FAIRDEALCompany”>
<finder-column name=”companyName” />
</finder>
<reference package-path=”com.liferay.counter” entity=”Counter” />
</entity>
<exceptions>
<exception>NoSuchMyCompany</exception>
</exceptions>
</service-builder>
3. Run build-service with “service.xml” as argument
a. go to “/ext/ext-impl”
b. execute “ant build-service -Dservice.file=src/com/testing/portlet/company/service.xml“
c. make sure the build is successful
d. confirm all the service layer files are generated as per the Spring/Hibernate framework. check under
ext/ext-impl/src/com/testing/portlet/company
ext/ext-service/src/com/testing/portlet/company
4. Copy the table “my_company.sql”
copy the my_company.sql file from ext/sql/portal_tables and past it to database “lportal“.
To run the SQL directly, you’ve to go to mysql prompt by giving “mysql -u root lportal“
create table my_company (
companyId LONG not null primary key,
companyName VARCHAR(75) null,
address VARCHAR(75),
startDate DATE null,
annualIncome DOUBLE,
stockQty DOUBLE,
active_ INTEGER,
);
5. Create Struts Action Portlet
5.1 portlet-ext.xml
<portlet>
<portlet-name>MyCompany</portlet-name>
<display-name>My Company</display-name>
<portlet-class>com.liferay.portlet.StrutsPortlet</portlet-class>
<init-param>
<name>view-action</name>
<value>/testing/company/view</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
5.2. liferay-portlet-ext.xml
<portlet>
<portlet-name>MyCompany</portlet-name>
<struts-path>testing/company</struts-path>
<use-default-template>false</use-default-template>
</portlet>
5.3. liferay-display.xml
<portlet id=”MyCompany” />
inside,
<category name=”category.MyCompany“>
5.4. struts-config.xml
<action path=”/testing/company/process“ type=”com.testing.portlet.company.action.ProcessMyCompanyAction“>
<forward name=”testing.company.view“ path=”testing.company.view” />
</action>
5.5. tiles-defs.xml
<definition name=”testing.company.view” extends=”portlet”>
<put name=”portlet_content” value=”/testing/company/view.jsp” />
</definition>
6. Update Service Layer Files:
add this method in MyCompanyLocalServiceImpl.java which is autogenerated ( in this path: com/testing/portlet/company/service/)
public MyCompany getCompanyName(String companyName) throws SystemException, PortalException{
return MyCompanyUtil.findByName(companyName);
}
import these files:
import com.testing.portlet.company.service.persistence.MyCompanyUtil;
import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
then give ant build-service inside ext-impl
7. Update / Create these Jsp / Java Files:
(jsp files path: ext-web/docroot/html/testing/company)
a. view.jsp
<%@ include file=”/html/testing/company/init.jsp” %>
<div id=”MYCOMPANY”>
<%
String PAGE = (String) request.getAttribute(“PAGE”);
System.out.println(“PAGE value is >>>>” + PAGE);
%>
<div id=”MYCOMPANY_CONTENT”>
<jsp:include page=”<%= PAGE %>” />
</div>
</div>
<% SessionMessages.clear(request); %>
a. add_company.jsp
<%@ include file=”/html/testing/company/init.jsp” %>
<form action=”" method=”post” name=”<portlet:namespace />fm” id=”<portlet:namespace />fm_id”>
<table width=”100%”> <tr>
<%if(SessionMessages.contains(session,”Added”)){%>
<td height=”15px”>
<div>
<liferay-ui:message key=”Record Added Successfully” />
</div>
</td>
<% } %>
</tr>
</table>
<table width=”100%” style=”border:1px solid lightblue” align=”center”>
<tr >
<td> Company Name: <%=star%></td>
<td colspan=”3″> <input style=”width:60%” type=”text” id=”<portlet:namespace />companyName” name=”<portlet:namespace />companyName“> </td>
</tr>
<tr class=’portlet-section-alternate results-row alt’>
<td> Address: </td>
<td colspan=”7″> <input style=”width:60%” type=”text” id=”<portlet:namespace />address” name=”<portlet:namespace />address”> </td>
</tr>
<tr class=’portlet-section-alternate results-row alt’>
<td> e Start Date: </td>
<td colspan=”7″> <input style=”width:60%” type=”text” id=”<portlet:namespace />startDate” name=”<portlet:namespace />startDate“> </td>
</tr>
<tr class=’portlet-section-alternate results-row alt’>
<td> Annual Income: </td>
<td colspan=”7″> <input style=”width:60%” type=”text” id=”<portlet:namespace />annualIncome” name=”<portlet:namespace />annualIncome“> </td>
</tr>
<tr class=’portlet-section-alternate results-row alt’>
<td> Stock Qty: </td>
<td colspan=”7″> <input style=”width:60%” type=”text” id=”<portlet:namespace />stockQty” name=”<portlet:namespace />stockQty“> </td>
</tr>
<tr class=’portlet-section-alternate results-row alt’>
<td> Active : </td>
<td colspan=”7″> <input style=”width:60%” type=”text” id=”<portlet:namespace />active” name=”<portlet:namespace />active“> </td>
</tr>
<tr>
<td colspan=”2″ align=”center”>
<input type=”submit” value=”Submit” id=”<portlet:namespace />submit“/>
<input type=”button” value=”Cancel” onclick=”addCompany()” id=”<portlet:namespace />Cancel” >
</td>
</tr>
</table>
b. company.jsp ( javascript file)
<script language=”Javascript”>
jQuery(document).ready(function() {
jQuery.metadata.setType(“attr”, “validate”);
var validator = jQuery(“#<portlet:namespace/>fm_id”).validate({
rules: {
<portlet:namespace/>companyName:{
required:true,
maxlength:75
}
},
messages: {
<portlet:namespace/>companyName:”Enter Valid Company Name “,
},
errorPlacement: function(error, element) {
error.appendTo(element.parent());
},
submitHandler: function() {
SubmitForm(document.<portlet:namespace />fm, ‘<portlet:actionURL windowState=”<%= WindowState.NORMAL.toString() %>”><portlet:param name=”struts_action” value=”/testing/company/process“/><portlet:param name=”CMD” value=”add_company” /></portlet:actionURL>’, ‘MYCOMPANY‘, false);
},
success: function(label) {
label.html(“ ”).addClass(“checked”);
}
});
});
</script>
c. init.jsp
<%@ include file=”/html/common/init.jsp” %>
<%– Add these jquery plugins –%>
<script src=”/html/js/jquery/jquery.metadata.js” type=”text/javascript”></script>
<script src=”/html/js/jquery/jquery.delegate.js” type=”text/javascript”></script>
<script src=”/html/js/jquery/jquery.validate.js” type=”text/javascript”></script>
<script src=”/html/js/jquery/jquery.js” type=”text/javascript”></script>
<%@ include file=”/html/testing/company/company.jsp” %>
<%
PortletPreferences prefs = renderRequest.getPreferences();
PortletSession pses = renderRequest.getPortletSession();
Calendar cal = Calendar.getInstance();
themeDisplay.setIncludeCalendarJs(true);
%>
(java files path: ext-impl/src/com/testing/portlet/company/action/ProcessMyCompanyAction.java)
d. ProcessMyCompanyAction.java
import these files :
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.struts.PortletAction;
import com.liferay.portlet.ActionRequestImpl;
import com.liferay.portlet.ActionResponseImpl;
import com.liferay.counter.service.CounterServiceUtil;
import com.liferay.portal.kernel.util.Validator
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletSession;
import javax.portlet.PortletURL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.testing.portlet.company.model.MyCompany;
import com.testing.portlet.company.service.MyCompanyLocalServiceUtil;
import com.testing.portlet.company.service.MyCompanyServiceUtil;
public class ProcessMyCompanyAction extends PortletAction {
private static Log log = LogFactory.getLog(ProcessMyCompanyAction.class);
public void processAction(ActionMapping mapping, ActionForm form, PortletConfig portletConfig, ActionRequest req,
ActionResponse res) throws Exception {
PortletURL url = ((ActionResponseImpl) res).createRenderURL();
url.setParameter(“struts_action”, “/testing/company/view”);
String cmd = ParamUtil.getString(req,”CMD”);
HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest();
PortletSession ses = req.getPortletSession();
HttpSession httpSession = httpReq.getSession();
log.info(“ProcessMyCompanyAction CMD Value >> “+cmd);
Date date = new Date();
MyCompany company = null;
long companyId = 0;
// company Name Duplicate Verification
String companyName = ParamUtil.getString(req,”companyName”);
String findCompanyName = “”;
try {
company = MyCompanyLocalServiceUtil.getCompanyName(companyName);
findCompanyName = company.getCompanyName();
}catch(Exception e) {
log.info(“CompanyName Not EXIST”);
}
log.info(“companyName” + companyName);
log.info(“findCompanyName” + findCompanyName);
if (Validator.isNotNull(cmd) && cmd.equalsIgnoreCase(“add_company“)) {
if (Validator.isNull(findCompanyName)) {
// set all fields into database
companyId = CounterServiceUtil.increment();
company = MyCompanyLocalServiceUtil.createMyCompany(companyId);
company.setCompanyName(ParamUtil.getString(req,”companyName”));
company.setActive(ParamUtil.getInteger(req,”active”));
company.setAddress(ParamUtil.getString(req,”address”));
company.setAnnualIncome(ParamUtil.getDouble(req,”annualIncome”));
company.setStockQty(ParamUtil.getString(req,”stockQty”));
company.setStartDate(ParamUtil.getString(req,”startDate”));
MyCompanyLocalServiceUtil.updateMyCompany(company);
SessionMessages.add(httpReq, “Added”);
} else {
SessionMessages.add(httpReq, “DuplicateCompanyName”);
}
res.sendRedirect(url.toString());
}
}
e. ViewMyCompanyAction.java
public class ViewMyCompanyAction extends PortletAction{
private static Log log = LogFactory.getLog(ViewMyCompanyAction.class);
public ActionForward render(
ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
RenderRequest req, RenderResponse res)
throws Exception {
HttpServletRequest httpReq = ((RenderRequestImpl) req).getHttpServletRequest();
PortletSession ses = req.getPortletSession();
HttpSession httpSession = httpReq.getSession();
String cmd = ParamUtil.getString(req,”CMD”);
req.setAttribute(“PAGE”, “/html/testing/company/add_company.jsp”);
return mapping.findForward(“testing.portlet.company.view”);
}
}
import these files:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.liferay.portlet.RenderRequestImpl;
import javax.portlet.PortletConfig;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;