11/23/2013

Introduction to Primefaces Client - Server interaction

Primefaces is a very powerful tool when it comes to client - server interaction. It allows us to call backend methods from javascript and it also makes reacting in javascript code to the outcome of bean methods very easy. This little tutorial will show you how to implement it. And yes - this also works in liferay. And it opens some interesting views of Inter-Portlet Communication.

Calling Java Methods from JavaScript

If you want to trigger a backend method from javascript you can simply add this tag to your jsf code:

<p:remotecommand actionlistener="#{bean.method}" name="callme"/>
This creates a javascript method name 'callme', that you can call from other javascript methods or (for example) from your "oncomplete" property of your commandButtons. Calling that method will call your backing bean method that may look like this :
public void method(){
  //do important stuff
}

Returning Objects to JavaScript 

If you now want to return data from your method you can do it like that:
public void method(){
  RequestContext context = RequestContext.getCurrentInstance(); 
  context.addCallbackParam("testparmeter", new String("test"));
}
This returns our teststring to the javascript method and if you return the call from your commandlink like this :
<p:commandLink action="#{bean.method}" oncomplete="handleShow(xhr, status, args);)"/>
Then you can access your property in javascript like this:
<script type="text/javascript">  

function handleShow(xhr, status, args) { 

alert(args.testparmeter);

}
</script>
 
Executing JavaScript from Backing Bean 

If you want to execute Javascript methods from your backing bean, then you can use the RequestContext, too. Just like in this example:
public void method(){
  RequestContext context = RequestContext.getCurrentInstance(); 
  context.execute("alert('test alert')");
}
This offers a complete set of tools and techniques for you to realize almost every aspect of Client-Server interaction. Because it actually creates javascript methods you can use this to allow Inter Portlet Communication between Primefaces Portlets. Just use two primefaces remoteCommands in two different portlets and you should be able to call them from the portlet´s JSF or Java ressources. You can then send data from portlet 1 to portlet 2 :)

If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)
If you have any questions, feel free to leave a comment.