Objective:
Update the content in portlet for particular intervals.
Environment:
Liferay 6.2 +Tomcat 7.x+MySQL 5.1
Note:
The code will work for portal 6.2 version you can try for 6.1 too.
Download Content Auto Update Portlet from following location
You can find source and war file
Portlet Screen:
Procedure for deploy portlet:
You can use war file and directly place in your portal deploy folder and test or you can also use source to deploy portlet.
Once portlet is deployed successfully you can see the portlet in sample category name as Content Auto Update.
Introduction:
Some time we may get requirement to update content in portlet for every particular intervals from server. To do this job we will use Ajax call to update content on portlet
What is Set Interval method?
Native java script has set interval method from this we can execute some task for each particular interval.
What is Ajax call?
Ajax is way of calling server content without page refresh in the browser. This will help us to avoid whole page loading for a little content update.
Ajax will help us to update particular part of web page with server side content or dynamic content.
This Ajax mechanism is implemented in client side java script. We have rich Ajax implemented java script libraries in market
The following are popular
AUI, YUI, DOJO, Prototype and ExtJS |
Note:
Liferay have inbuilt support for AUI script.
What is Serve Resource Method?
Server Resource method is meant for serving some resource or content from server in portlet technology. This method helps us to serve images, files, JSON data and XML data from server.
This method especially we will use with Ajax call to get content from server.
Implementation
Assume we want update users data in page for every particular interval. We will use Ajax and set interval methods to complete this job.
We will use jQuery library to implement Ajax in liferay. JQuery is very popular java script library in market.
Steps:
- Load jQuery library in JSP page
- Create server Resource URL
- Implement Serve Resource Method to serve Dynamic content
- Use jQuery Ajax method with serve resource URL
- Use Set Interval method to call Ajax
Load jQuery Library in JSP page
We want use jQuery in JSP page we have to load jQuery java script in JSP page so that we can use jQuery.
We will use scrip tag to load java script in JSP page
The following is script tag to load jQuery in JSP page
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> |
Create server Resource URL
Server Resource URL is meant for call the server resource method from Portlet Action class.
We will use this URL in Ajax call. This we will call it as destination URL for Ajax
We will use portlet URL tag to create serve resource URL
The following is serve resource URL
<portlet:resourceURL var="updaContentURL"> </portlet:resourceURL> |
Note:
If we want use portlet tags we have to include following tag in JSP page.
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %> |
Implement Serve Resource Method to serve Dynamic content
Now we have to override serve Resource method in portlet action class this method will serve the dynamic content as response.
When we is server Resource URL call it will execute serve Resource in portlet action class.
This is the place our business logic should be present.
The following is example
@Override public void serveResource(ResourceRequest resourceRequest,ResourceResponse resourceResponse)throws IOException, PortletException { try { System.out.println("====serveResource========"); JSONObject jsonUser=null; JSONArray usersJsonArray=JSONFactoryUtil.createJSONArray(); List<User> userList=UserLocalServiceUtil.getUsers(1, UserLocalServiceUtil.getUsersCount()); for(User userObj:userList){ jsonUser=JSONFactoryUtil.createJSONObject(); jsonUser.put("firstName",userObj.getFirstName()); jsonUser.put("lastName",userObj.getLastName()); jsonUser.put("email",userObj.getEmailAddress()); jsonUser.put("screeName",userObj.getScreenName()); usersJsonArray.put(jsonUser); } PrintWriter out=resourceResponse.getWriter(); System.out.println(usersJsonArray.toString()); out.print(usersJsonArray.toString()); } catch (Exception e) { e.printStackTrace(); } } |
Note:
Here we need JSON as response data so we will use JSON objects to server JSON data as response.
Use jQuery Ajax method with serve resource URL
Now we will use jQuery Ajax method to get content from server and we will update in page.
JQuery Ajax need destination URL so we will use server resource URL.
And we also need to mention what kind of data we required here we will JSON as response data the following is jQuery Ajax Call
//on ready load required java script when load page $(document).on('ready',function(){ //jquey aja methos to call server side content $.ajax({ url: '<%=updaContentURL%>', dataType: "json", data:{}, type: "get", success: function(data){ //here response data will come and we need to update in the page. }, beforeSend: function(){ // it will execute before Ajax call start }, complete: function(){ // this method will execute after success method is completed. }, error: function(){ } }); }); |
Use Set Interval method to call Ajax
We will use java script native set interval method this will execute the task for each particular intervals
The following is syntax
<script> $(document).on('ready',function(){ //this is set interval method which call the update method for every 30 seconds means 3000 milli seconds setInterval(updateDiv,3000); //Upadate method function updateDiv(){ //Here we will call Ajax method } }); |
The following is complete code
Write following code in JSP page
<%@ include file="init.jsp"%> <style> #usersTable td{ width:150px; font-size: 12px; font-weight: bold; } </style> <portlet:resourceURL var="updaContentURL"> </portlet:resourceURL> <div id="userContent"> <table id="usersTable" border="1"> </table> </div> <div id="wait" style="display: none; width: 69px; height: 89px; border: 1px solid black; position: absolute; top: 50%; left: 50%; padding: 2px;"> <img src='http://www.w3schools.com/jquery/demo_wait.gif' width="64" height="64" /><br>Loading.. </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(document).on('ready',function(){ //this is set interval method which call the update method for every 30 secends means 3000 milli seconds setInterval(updateDiv,3000); //Upadate method function updateDiv(){ var allRows=""; //ajac call to get updated content $.ajax({ url: '<%=updaContentURL%>', dataType: "json", data:{}, type: "get", success: function(data){ $.each(data,function(idx, obj){ var tableRow='<tr><td>'+obj.screeName+'</td><td>'+obj.firstName+'</td><td>'+obj.lastName+'</td><td>'+obj.email+'</td></tr>'; allRows=allRows.trim()+tableRow.trim(); }); }, beforeSend: function(){ $("#wait").css("display","block"); }, complete: function(){ $("#wait").css("display","none"); $('#usersTable').empty(); $('#usersTable').html(allRows.trim()); }, error: function(){ $('#userContent').html('<span style="color:red">Connection problems</span>'); } }); } }); </script> |
The following is Serve Resource method in portlet action class
package com.meera.contentautoupdate; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.portlet.PortletException; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import com.liferay.portal.kernel.json.JSONArray; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.model.User; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.util.bridges.mvc.MVCPortlet; public class ContentAutoUpdateAction extends MVCPortlet { @Override public void serveResource(ResourceRequest resourceRequest,ResourceResponse resourceResponse)throws IOException, PortletException { try { System.out.println("====serveResource========"); JSONObject jsonUser=null; JSONArray usersJsonArray=JSONFactoryUtil.createJSONArray(); List<User> userList=UserLocalServiceUtil.getUsers(1, UserLocalServiceUtil.getUsersCount()); for(User userObj:userList){ jsonUser=JSONFactoryUtil.createJSONObject(); jsonUser.put("firstName",userObj.getFirstName()); jsonUser.put("lastName",userObj.getLastName()); jsonUser.put("email",userObj.getEmailAddress()); jsonUser.put("screeName",userObj.getScreenName()); usersJsonArray.put(jsonUser); } PrintWriter out=resourceResponse.getWriter(); System.out.println(usersJsonArray.toString()); out.print(usersJsonArray.toString()); } catch (Exception e) { e.printStackTrace(); } } } |
Important Points
- Ajax is way of calling server side content without whole page refresh and it will used to update part of web content.
- Server Resource method will server images, files and particular format data from server.
- Set Interval is method in native java script which will call task for each interval.
Reference Links
http://api.jquery.com/jquery.ajax/
http://www.liferaysavvy.com/2014/11/liferay-requires-name-spaced-parameters.html
http://www.liferaysavvy.com/2014/11/liferay-requires-name-spaced-parameters.html
Author
Meera Prince
0 comments:
Post a Comment