| Liferay, Portlets and Ajax |
|
|
|
| Written by Josh B |
| Wednesday, 09 February 2011 20:47 |
|
Following on from the previous entry, this post deals with using Ajax from Liferay Portlets. (This blog entry was inspired by various posts in the Liferay Community Forums.) One of the key reasons to use Ajax with Portlets is to preserve the immediacy of the dashboard. When you are dealing with Portlets it is undesirable to have the user refresh the entire Portal page. This is where Ajax comes in. It allows the user to start and complete actions while multi-tasking with other Portlets. One of the great things about Portlets is that Java already has a Portlet API (javax.portlet). The API can do many things, but one immediate benefit is that it makes AJAX much easier. We can extend javax.portlet.GenericPortlet and over-ride the methods we wish to use: package com.sample.jsp.portlet; Here we are over-riding both doView (to load the JSP Portlet page) and serveResource (to serve our response back to the JSP). "serveResource" is the method that is called when the JSP performs an AJAX request. If we were doing this for real we would be responding with XML, JSON, or some kind of machine readable message. We now need to point the Portlet at this class so it knows to use it. So in src/main/webapp/WEB-INF/portlet.xml we need to do the following: <!-- <portlet-class>com.liferay.util.bridges.mvc.MVCPortlet</portlet-class> --> This points the Portlet to our own Portlet class. Finally, we need to write a JSP that uses AJAX in some way. Put the following in view.jsp: <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %> Then deploy this and make sure you are using the most current version. When you click on the "Press Me" button the value of the input box will be sent to the JSPPortlet class, and then echoed straight back to the Portlet. The Portlet will then attach the text received to the "content" div. You should see the message you just entered embedded in the Portlet. All this should happen without refreshing the Portlet container. And that's Liferay Portlets with AJAX.
Top Tip: If you want to use JQuery in your Portlet, add the following to src/main/webapp/WEB-INF/liferay-portlet.xml <header-portlet-javascript>http://code.jquery.com/jquery-1.4.3.min.js</header-portlet-javascript>
|
| Last Updated on Wednesday, 09 February 2011 21:19 |




