JSF Portlet Database Interaction Copyright © 2000-2006 Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in print without written permission from Liferay, Inc. Special Note • This exercise will not work with any version of Liferay before 4.2.2 • In order to access a new service in the service layer in Liferay from a portlet war, you must use the code from a Liferay build after version 4.2.1. • An update to SVN trunk will allow this example to work. Objective The goal of this tutorial is to add Database interaction to the JSF Portlet. 1. Create a database structure – service.xml 2. Auto generating the Service Layer code and SQL – build.xml – build-service 3. Modifying MySQL to include new table – portal-tables.sql 4. Create method to add record to the database – 5. BookLocalServiceImpl.java Retrieve records from the database – BookLocalServiceImpl.java service.xml • Locate the current service.xml file in the C:\training\liferay\ext\ext-ejb\ directory • Move service.xml to the reports directory: …\ext\ext-ejb\src\com\ext\portlet\reports • Go back to the \ext\ext-ejb\ directory • Create a new service.xml file in …\ext\ext-ejb\ service.xml contents <?xml version="1.0"?> <!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 4.0.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_4_0_0.dtd"> <service-builder root-dir=".." package-path="com.ext.portlet"> <portlet name="Library" short-name="Library" /> <entity name="Book" local-service="true"> <!-- PK fields --> <column name="bookId" type="String" primary="true" /> <!-- Permission Fields --> <column name="companyId" type="String" /> <column name="groupId" type="String" /> <column name="userId" type="String" /> <!-- Audit fields --> <column name="createDate" type="Date" /> <column name="modifiedDate" type="Date" /> <!-- Other fields --> <column name="title" type="String" /> </entity> </service-builder> Overview of service.xml • package-path="com.ext.portlet“ is the path that the class will generate to C:\Training\liferay\ext\ext-ejb\src\com\ext\portlet • <portlet name="Library" short-name="Library" /> is used to generate a new package called “com.ext.portlet.library” in your source directory C:\Training\liferay\ext\ext-ejb\src\ • <entity name="Book" local-service="true"> is the Database table you want to create and then link up to in the code Checkpoint • The generation of the service layer code is all automated. • Navigate to the …\ext\ext-ejb\ directory • Make sure your service.xml file is formatted correctly Generate Service Layer Code 1. 2. 3. 4. Click Start Run… Type cmd and press Enter Navigate to C:\Training\liferay\ext\ext-ejb\ Type ant build-service in the command prompt. Generated Service Layer Results portal-tables.sql Updated • • As part of the auto generation, portal-tables.sql was updated to include our new Book table portal-tables.sql is located here: …\ext\sql\portal-tables.sql This was added to portal-tables.sql: • create table Book ( • bookId VARCHAR(75) not null primary key, companyId VARCHAR(75) not null, groupId VARCHAR(75) not null, userId VARCHAR(75) not null, createDate DATE null, modifiedDate DATE null, title VARCHAR(75) null ); • Remember to click Refresh on the “ext” directory after running build-service to see the newly generated files! Update our database called “training” 1. Click Start Run… 2. Type cmd and press Enter 3. Type mysql and press Enter 4. Type use training; and press Enter 5. Type show tables; and press Enter Confirm that the “Book” table does not exist yet Updating Our Database • Copy the generate SQL code: create table Book ( bookId VARCHAR(75) not null primary key, companyId VARCHAR(75) not null, groupId VARCHAR(75) not null, userId VARCHAR(75) not null, createDate DATE null, modifiedDate DATE null, title VARCHAR(75) null ); • Paste it into the Cmd prompt Confirm the Update • Type show tables; and press Enter Confirm that the “Book” table exist now Creating the Service Layer Class • Navigate to: C:\Training\liferay\ext\ext-ejb\src\com\ext\portlet\library\service\impl\ • Open BookLocalServiceImpl.java • We are going to add the database insert method to this service layer class. BookLocalServiceImpl.java Content package com.ext.portlet.library.service.impl; import java.util.Date; import com.ext.portlet.library.model.Book; import com.ext.portlet.library.service.persistence.BookUtil; import com.liferay.counter.service.CounterLocalServiceUtil; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.ext.portlet.library.service.BookLocalService; public class BookLocalServiceImpl implements BookLocalService { public Book addBook(String userId, String title) throws PortalException, SystemException { Book book = BookUtil.create(Long.toString(CounterLocalServiceUtil.increment(Book.class.getName()))); Date now = new Date(); book.setCreateDate(now); book.setModifiedDate(now); book.setUserId(userId); book.setTitle(title); return BookUtil.update(book); } } Regenerate Service Layer Code 1. 2. 3. 4. 5. Click Start Run… Type cmd and press Enter Navigate to C:\Training\liferay\ext\ext-ejb\ Type ant build-service in the command prompt. The wrapper classes have been generated. Regenerated Service Layer Results Deploy the Files to Tomcat Deploy files to Tomcat once you are finished • Open up a cmd prompt – Click “Start”, “Run” and then type “cmd” • Navigate to your ext directory and then type “ant deploy” • …\ext>ant deploy Implement Event Handler This method will add a book to the Library, using the Library Service. It will also create confirmation and error messages as appropriate. Modify BookBean.java: BookBean.java Content package com.ext.portlet.library.ui; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import com.ext.portlet.library.service.BookLocalServiceUtil; public class BookBean { public String getTitle() { return _title; } public void setTitle(String title) { _title = title; } public void addBook(ActionEvent actionEvent) { // clear the title FacesContext facesContext = FacesContext.getCurrentInstance(); try { BookLocalServiceUtil.addBook(facesContext.getExternalContext().getRemoteUser(), getTitle()); } catch (Exception e) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error adding book.", e.toString()); facesContext.addMessage(null, message); e.printStackTrace(); return; } FacesMessage message = new FacesMessage(getTitle() + " was added successfully."); // null signifies that this message is not intended for any ui component facesContext.addMessage(null, message); // clear the title setTitle(""); } public String displayBooks() { return "success"; } private String _title; } Deploy the Files to Tomcat • • • • Compile Deploy Refresh Verify Final Steps 1. Restart Tomcat 2. Open up a new browser and type http://localhost:8080 LOGIN: test@liferay.com PASSWORD: test Verify the data in the database 1. Click Start Run… 2. Type cmd and press Enter 3. Type mysql and press Enter 4. Type use training; and press Enter 5. Type select * from book; and press Enter Checkpoint • Update the existing JSP files to use the generated Service and Persistence Layer Classes • Added a book title in the JSF Portlet • Confirmed that the book title was added successfully in to the database Retrieving Records • Retrieving records from the data base will include updating a Service Layer Class and regenerating the wrapper classes • We will add a getAll() method to BookLocalServiceImpl.java • Regenerate the Service and Persistence Layer classes • We will update display_books.jsp to retrieve and display the book title records BookLocalServiceImpl.java • Add a getAll() method public List getAll() throws PortalException, SystemException { return BookUtil.findAll(); } • import java.util.List; • Regenerate the Service Layer to create a wrapper class for getAll() BookLocalServiceImpl.getAll() In …/ext/ext-ejb, modify com.ext.portlet.library.service.impl.BookLocalServiceImpl BookLocalServiceImpl.java Content package com.ext.portlet.library.service.impl; import java.util.List; import java.util.Date; import com.ext.portlet.library.model.Book; import com.ext.portlet.library.service.persistence.BookUtil; import com.liferay.counter.service.CounterLocalServiceUtil; import com.liferay.portal.PortalException; import com.liferay.portal.SystemException; import com.ext.portlet.library.service.BookLocalService; public class BookLocalServiceImpl implements BookLocalService { public Book addBook(String userId, String title) throws PortalException, SystemException { Book book = BookUtil.create(Long.toString(CounterLocalServiceUtil.increment(Book.class.getName()))); Date now = new Date(); book.setCreateDate(now); book.setModifiedDate(now); book.setUserId(userId); book.setTitle(title); return BookUtil.update(book); } public List getAll() throws PortalException, SystemException { return BookUtil.findAll(); } } Regenerate Service Layer Code 1. 2. 3. 4. 5. Click Start Run… Type cmd and press Enter Navigate to C:\Training\liferay\ext\ext-ejb\ Type ant build-service in the command prompt. The wrapper classes have been generated. Regenerated Service Layer Results Deploy the Files to Tomcat • • • • Compile Deploy Refresh Verify Add BookBean.getAllBooks() Modify BookBean.java: BookBean.java Content package com.ext.portlet.library.ui; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import com.ext.portlet.library.service.BookLocalServiceUtil; public class BookBean { public String getTitle() { return _title; } public void setTitle(String title) { _title = title; } public void addBook(ActionEvent actionEvent) { // clear the title FacesContext facesContext = FacesContext.getCurrentInstance(); try { BookLocalServiceUtil.addBook(facesContext.getExternalContext().getRemoteUser(), getTitle()); } catch (Exception e) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error adding book.", e.toString()); facesContext.addMessage(null, message); e.printStackTrace(); return; } FacesMessage message = new FacesMessage(getTitle() + " was added successfully."); // null signifies that this message is not intended for any ui component facesContext.addMessage(null, message); // clear the title setTitle(""); } public String displayBooks() { return "success"; } public List getAllBooks() { List books = new ArrayList(); try { books = BookLocalServiceUtil.getAll(); } catch (Exception e) { } return books; } private String _title; } Deploy the Files to Tomcat • • • • Compile Deploy Refresh Verify display_books.jsp updates Add presentation logic to display the book Modify …/portlets/library_jsf_portlet.war/display_b ooks.jsp: display_books.jsp updates <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <h1> Display Books </h1> <h:dataTable headerClass="portlet-section-header" rowClasses="portlet-section-body,portlet-section-header-alternate" value="#{book.allBooks}" var="bookItem"> <h:column> <f:facet name="header"> <h:outputText value="Title"/> </f:facet> <h:outputText value="#{bookItem.title}"/> </h:column> display_books.jsp HTML code <h:column> <f:facet name="header"> <h:outputText value="User ID"/> </f:facet> <h:outputText value="#{bookItem.userId}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Create Date"/> </f:facet> <h:outputText value="#{bookItem.createDate}"> <f:convertDateTime type="both" dateStyle="short" timeStyle="short"/> </h:outputText> </h:column> </h:dataTable> <br/> <br/> <h:form> <h:commandButton action="back" value="Back"/> </h:form> Deploy the Files to Tomcat • • • • Compile Deploy Refresh Verify Final Steps 1. Restart Tomcat 2. Open up a new browser and type http://localhost:8080 LOGIN: test@liferay.com PASSWORD: test Review Key Concepts • Create your table structure in service.xml • Generate Service and Persistence Layer Classes with Ant’s Build-Service • Add methods to the Impl Service Class to generate a wrapper method in the Util Class • Implement in BookBean.java • Add code in your JSP file to display data Revision History Jerry Niu 9/7/2006-9/11/2006 - Slide create and updates Scott Lee 10/30/2006 - updated slides to include permissions fields in service.xml Scott Lee 12/9/2006 - corrected code for success.jsp 01/17/2007 - Convert for JSF James Min
© Copyright 2024