How to call JSF managed bean method using javascript. p:remotecommand example

Do you need to call JSF managed bean method using javascript?. Then you can use primefaces <p:remoteCommand/>. In this tutorial, let us see how to call JSF managed bean method from javascript. This tutorial also covers how to pass additional parameters to the bean method using javascript. In General, JSF backing bean/managed bean method is called by command button action/actionListner attribute. Now let us see how to call bean method with primefaces remoteCommand tag using javascript.  In this example, I have created a maven  project (JSF2Demo) in eclipse.

jsf remote command

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JSF2Demo</groupId>
	<artifactId>JSF2Demo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>JSF2Demo Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.2.11</version>
		</dependency>

		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.2.11</version>
		</dependency>
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>5.2</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>JSF2Demo</finalName>
	</build>
</project>

 

Now We will see two examples using p:remoteCommand

1. Simply calling managed bean method using javascript when the JSF page loads.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">


<h:head>
	<title>JSF remoteCommand Example</title>
</h:head>
<h:body>
	<h3></h3>
	<h:form>
		<p:remoteCommand name="callRemoteMethod"
			actionListener="#{userBean.myBeanMethod}" />

		<h:outputText value="Now calling myBeanMethod" />
	</h:form>

	<script type="text/javascript">
		callRemoteMethod(); //makes a remote call of managed bean method
	</script>

</h:body>
</html>

When we  use remoteCommand tag, JSF creates a javascript function ( i.e. in our example callRemoteMethod) that matches the name of remoteCommand tag. Now we need to call this function from script which calls the bean method.

2. In the second example, managed bean method is called with additional parameters using client side script on click event. Let us see an example of simple user registration page having two command buttons.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">


<h:head>
	<title>JSF Client Example</title>
</h:head>
<h:body>
	<h3>Item Master</h3>
	<h:outputScript library="js" name="script.js" target="head"></h:outputScript>
	<h:form>
		<h:outputLabel> User Id</h:outputLabel>
		<h:inputText value="#{userBean.userId}"></h:inputText>
		<h:outputLabel> User Name</h:outputLabel>
		<h:inputText value="#{userBean.name}"></h:inputText>
		<h:outputLabel>Email</h:outputLabel>
		<h:inputText value="#{userBean.email}"></h:inputText>
		<h:outputLabel>Mobile Number</h:outputLabel>
		<h:inputText value="#{userBean.mobileNo}"></h:inputText>

		<h:outputLabel />
		<h:commandButton value="Verify by Email" action="#{userBean.verify}"
			ajax="false">
		</h:commandButton>
		<p:remoteCommand name="sendOtp" update="msgs"
			action="#{userBean.verify}" ajax="false" />

		<p:growl id="msgs" showDetail="true" />
		<h:commandButton type="button" value="Verify by Mobile"
			onclick="verifyByMobile()" icon="ui-icon-refresh" ajax="false" />
	</h:form>
</h:body>
</html>

in JavaScript, write the below function. In this example, I have created script.js with the below code and placed the js file  under the webapp/resources/js folder.

function verifyByMobile(){
	
	
	sendOtp([{name:'OTP', value:true}]);
	
}

In the above JSF page, both command buttons call the same bean method called verify. The second button (Verify by Mobile) calls the javascript function verifyByMobile() that calls sendOtp() function which calls the bean method (verify )with aditional parameter “OTP“.

The UserBean class code is given below.

package net.javaonline.jsf;

import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class UserBean {

	
	private String userId;
	private String name;
	private String email;
	private String mobileNo;
	private String disp1;

	public String getDisp1() {
		return disp1;
	}

	public void setDisp1(String disp1) {
		this.disp1 = disp1;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String verify()

	{

		FacesContext context = FacesContext.getCurrentInstance();

		//to retrieve additional parameter
		Map<String, String> params = context.getExternalContext()
				.getRequestParameterMap();
		String sendOtpFlag = params.get("OTP") != null ? params.get("OTP") : "";  // additional parameter to decide Verification by Email or Verification by Mobile

		if (sendOtpFlag.equals("true")) {
			System.out.println("OTP called");
			return "getotp";
		} else {
			// Code to send verification link through email
			System.out.println("Email Verification called");
			return "success";
		}

	}

	public void myBeanMethod() {
		System.out.println("My Bean Method Called when loading the JSF page");
	}

}

Reference : PrimeFaces remoteCommand tag

Leave a Reply