JSF 2.x - Basic Flot Chart Example


This is a basic example which shows how to use flot charts in jsf 2.x.

We draw a basic line chart. The data for this charts comes from a managed bean. We are using the ui:repeat tag to generate the javascript  for the chart dynamically.

Flot Chart Integration in a JSF 2.x Project

To start, create a JSF 2.x project and copy the flot chart library to the webapp root folder.

Flot Charts Integration in JSF 2.x

Managed Bean

package com.jsfcharts;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class ChartBean {
    
    private List<Double> values;
    
    @PostConstruct
    public void init() {
        values = new ArrayList<>();
        values.add(10d);
        values.add(12d);
        values.add(11.5);
        values.add(13d);
        values.add(12.5);
        values.add(15d);
    }

    public List<Double> getValues() {
        return values;
    }

    public void setValues(List<Double> values) {
        this.values = values;
    }
}

JSF Page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Basic Flot Chart Example</title>
    </h:head>
    <h:body>

        <h:outputStylesheet>

            .demo-container {
            border: 1px solid #ddd;
            height: 450px;
            margin: 15px auto 30px;
            padding: 20px 15px 15px;
            width: 850px;
            }
            .demo-placeholder {
            font-size: 14px;
            height: 100%;
            width: 100%;
            }

        </h:outputStylesheet>

        <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
        <script language="javascript" type="text/javascript" src="flot/jquery.min.js"></script>
        <script language="javascript" type="text/javascript" src="flot/jquery.flot.js"></script>
        <script type="text/javascript">

            $(function () {

                var d1 = [];
                var i=0;
                
                <ui:repeat value="#{chartBean.values}" var="value">
                    d1.push([i++, #{value}]);
                </ui:repeat>

                $.plot("#placeholder", [d1]);
                
            });

        </script>        
        
        <div class="demo-container">
            <div id="placeholder" class="demo-placeholder"></div>
	</div>        

    </h:body>
</html>

Result