Close

Spring Boot Primefaces Integration

[Last Updated: Sep 10, 2020]

Following example shows how to use Primefaces with Spring Boot.

Example

pom.xml

pom.xml

<project .....>
<modelVersion>4.0.0</modelVersion>

<groupId>com.logicbig.example</groupId>
<artifactId>boot-primefaces-integration-example</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
</parent>

<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>8.0</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.20</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.20</version>
</dependency>

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.3.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

A managed bean

In Spring Boot application, a JSF managed bean is also a Spring bean.

package com.logicbig.example;

import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.LineChartModel;
import org.primefaces.model.chart.LineChartSeries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@Component
@ManagedBean
@ViewScoped
public class LineChartBean {
  @Autowired
  private DataService dataService;
  private LineChartModel lineModel;

  @PostConstruct
  public void init() {
      lineModel = new LineChartModel();
      LineChartSeries s = new LineChartSeries();
      s.setLabel("Population");

      dataService.getLineChartData().forEach(s::set);

      lineModel.addSeries(s);
      lineModel.setLegendPosition("e");
      Axis y = lineModel.getAxis(AxisType.Y);
      y.setMin(0.5);
      y.setMax(700);
      y.setLabel("Millions");

      Axis x = lineModel.getAxis(AxisType.X);
      x.setMin(0);
      x.setMax(7);
      x.setTickInterval("1");
      x.setLabel("Number of Years");

  }

  public LineChartModel getLineModel() {
      return lineModel;
  }
}

DataService

package com.logicbig.example;

import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class DataService {

  public Map<Integer, Double> getLineChartData() {
      Map<Integer, Double> map = new LinkedHashMap<>();
      map.put(1, 5.20);
      map.put(2, 19.63);
      map.put(3, 59.01);
      map.put(4, 139.76);
      map.put(5, 300.4);
      map.put(6, 630.0);
     return map;
  }
}

Spring ELResolver

SpringBeanFacesELResolver allows us to use JSF managed beans as Spring beans and also to inject other spring beans there.

src/main/webapp/WEB-INF/faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
	version="2.2">

	<application>
		<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver
		</el-resolver>
	</application>

</faces-config>

JSF page

src/main/webapp/index.xhtml

<?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:h="http://java.sun.com/jsf/html"
	  xmlns:p="http://primefaces.org/ui"
	  xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
</h:head>

<h:body style="margin-left:50px">
	<h2>PrimeFaces Linear Chart Example</h2>
	<p:chart type="line" model="#{lineChartBean.lineModel}" style="height:400px;width:600px"/>
</h:body>
</html>

The Main class

Other than being main spring boot class, this class also registers JSF's FacesServlet vis ServletRegistrationBean.

package com.logicbig.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import javax.faces.webapp.FacesServlet;
import javax.servlet.ServletContext;
import java.util.Arrays;

@SpringBootApplication
public class Main{

  public static void main (String[] args) {
      SpringApplication.run(Main.class, args);
  }

  @Bean
  ServletRegistrationBean jsfServletRegistration (ServletContext servletContext) {
      //spring boot only works if this is set
      servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());

      //registration
      ServletRegistrationBean srb = new ServletRegistrationBean();
      srb.setServlet(new FacesServlet());
      srb.setUrlMappings(Arrays.asList("*.xhtml"));
      srb.setLoadOnStartup(1);
      return srb;
  }
}

Running the application

mvn spring-boot:run
mvn -q spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)

2020-09-10 23:25:56.288  INFO 6168 --- [           main] com.logicbig.example.Main                : Starting Main on DESKTOP-0E87003 with PID 6168 (D:\LogicBig\example-projects\spring-boot\boot-jsf-integration\boot-primefaces-integration-example\target\classes started by joe in D:\LogicBig\example-projects\spring-boot\boot-jsf-integration\boot-primefaces-integration-example)
2020-09-10 23:25:56.290  INFO 6168 --- [           main] com.logicbig.example.Main                : No active profile set, falling back to default profiles: default
2020-09-10 23:25:56.835  INFO 6168 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-09-10 23:25:56.843  INFO 6168 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-09-10 23:25:56.843  INFO 6168 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-10 23:25:57.044  INFO 6168 --- [           main] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2020-09-10 23:25:57.057  INFO 6168 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-09-10 23:25:57.057  INFO 6168 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 736 ms
2020-09-10 23:25:57.119  INFO 6168 --- [           main] j.e.resource.webcontainer.jsf.config     : Initializing Mojarra 2.2.20 ( 20190731-0757 59754ac80c05d61848a08939ddd11a324f2345ac) for context ''
2020-09-10 23:25:57.202  INFO 6168 --- [           main] j.e.r.webcontainer.jsf.application       : JSF1048: PostConstruct/PreDestroy annotations present.  ManagedBeans methods marked with these annotations will have said annotations processed.
2020-09-10 23:25:57.630  INFO 6168 --- [           main] .w.PostConstructApplicationEventListener : Running on PrimeFaces 8.0
2020-09-10 23:25:57.724  INFO 6168 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-10 23:25:57.833  INFO 6168 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-09-10 23:25:57.841  INFO 6168 --- [           main] com.logicbig.example.Main                : Started Main in 1.784 seconds (JVM running for 2.007)

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.3.3.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • primefaces 8.0: PrimeFaces is one of the most popular UI libraries in Java EE Ecosystem and widely used by software companies, world renowned brands, banks, financial institutions, insurance companies, universities and more. [Description from primefaces-8.0.pom]
  • jsf-api 2.2.20: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.20: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • tomcat-embed-jasper 9.0.37: Core Tomcat implementation.
  • JDK 1.8
  • Maven 3.5.4

Using Primefaces with SpringBoot Select All Download
  • boot-primefaces-integration-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • LineChartBean.java
          • webapp
            • WEB-INF

    See Also