Skip to content
javahacks.dev
JavaServer Faces

How to Use PrimeFaces Charts With Server Side Models

Draw bar, line and pie charts in JSF with PrimeFaces: build a ChartModel in a bean, bind p:chart, update it with AJAX, handle click events and size data.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the OpenJDK, HTML5 and Vaadin logos.

Reports and dashboards need charts, and PrimeFaces wraps Chart.js, so you describe the chart in Java and the component draws it in the browser. That division is the thing to understand: the server builds a model holding labels, numbers and options, the page renders it as JSON, and Chart.js does the drawing. This guide uses PrimeFaces 14 and JDK 25 to build a bar chart with an AJAX year selector, and then covers update patterns, click events and the data-size limits that decide whether a chart page stays fast. The page structure and the beans follow JSF basics.

A bar chart

java
@Named
@ViewScoped
public class SalesBean implements Serializable {

    private BarChartModel model;

    @Inject SalesService sales;

    @PostConstruct
    public void init() {
        build(2025);
    }

    public void build(int year) {
        Map<String, BigDecimal> byMonth = sales.totalsByMonth(year);

        ChartData data = new ChartData();
        BarChartDataSet dataSet = new BarChartDataSet();
        dataSet.setLabel("Revenue " + year);
        dataSet.setBackgroundColor("rgba(54, 162, 235, 0.6)");
        dataSet.setData(new ArrayList<>(byMonth.values()));
        data.addChartDataSet(dataSet);
        data.setLabels(new ArrayList<>(byMonth.keySet()));

        BarChartOptions options = new BarChartOptions();
        CartesianScales scales = new CartesianScales();
        CartesianLinearAxes y = new CartesianLinearAxes();
        y.setBeginAtZero(true);
        scales.addYAxesData(y);
        options.setScales(scales);

        model = new BarChartModel();
        model.setData(data);
        model.setOptions(options);
    }

    public BarChartModel getModel() { return model; }
}
XML
<h:form id="report">
  <p:selectOneMenu value="#{salesBean.year}">
    <f:selectItems value="#{salesBean.years}"/>
    <p:ajax listener="#{salesBean.onYear}" update="chart"/>
  </p:selectOneMenu>
  <p:chart id="chart" type="bar" model="#{salesBean.model}" style="width: 100%; height: 360px"/>
</h:form>

The type must match the model class: the bar type needs a BarChartModel. Other types are line, pie, doughnut, radar, polarArea, bubble and scatter, each with its own model class. Class names and setters have changed between PrimeFaces major versions, so check the showcase for the version you actually run, instead of copying from an older tutorial. The labels and the data list must be in the same order and the same length, or the chart silently misaligns values with months. Setting beginAtZero on the value axis keeps bars honest; a bar chart that starts at a high baseline exaggerates differences.

Build once, not on every render

A JSF getter can be called several times in one request. Do not query the database inside getModel().

java
public BarChartModel getModel() {
    return model;               // plain accessor
}

Build the model in @PostConstruct and in the AJAX listener, as above, and let the getter return the field. A query in a getter turns one page view into several identical queries, which is the same mistake as any heavy getter and connects to JSF performance. Because the bean is view-scoped, the model survives AJAX requests on the same page and is rebuilt only when the user changes the year.

Updating the chart

Changing the year runs onYear, which calls build(year) and replaces the model. The update="chart" attribute re-renders the component, and the browser redraws it with the new data. For live data, a p:poll with a modest interval refreshes the chart, but a poll per open page adds server load in proportion to the number of users, so keep the interval long, thirty seconds or more, and stop the poll when the tab is hidden. If many users need near-real-time updates, push them with WebSocket support instead of polling.

Interaction

Click events on a data point can call the server.

XML
<p:chart type="bar" model="#{salesBean.model}">
  <p:ajax event="itemSelect" listener="#{salesBean.onSelect}" update=":detail"/>
</p:chart>
java
public void onSelect(ItemSelectEvent event) {
    int month = event.getItemIndex();
    selectedMonth = month;
}

The event carries the index of the clicked bar and of its dataset, not the label, so look the month up from your own data. A natural use is to open a dialog showing the orders behind that bar. The colon in :detail makes the id absolute, so it works from outside the form.

Data size and performance

The chart's whole model is rendered into the page as JSON. A few hundred points are fine. Thousands slow the browser, bloat the response and make the view state larger. Aggregate on the server to a sensible number of points, for example daily totals instead of every transaction, and let the database do the grouping, because a group by over an indexed column is far cheaper than loading rows into Java; the technique for checking the query is in reading a query plan. Ten series of a thousand points each is the sort of volume to avoid.

Accessibility and export

The component offers no built-in table fallback, so provide a data table beside the chart for screen reader users and for anyone who wants the numbers. A p:dataTable bound to the same list does that, and for large data the lazy form in lazy data tables keeps it light. Colour alone should not carry meaning: use patterns or labels as well. The chart's own export options are limited, so build a CSV from the same data on the server when users need to download it.

Choosing the chart type

Pick the type from the question the chart answers. Compare quantities across categories with bars, show change over time with lines, and show shares of a whole with a pie only when there are few slices and the whole is meaningful; a doughnut with twelve slices tells nobody anything. A horizontal bar chart handles long category names better than vertical. When two quantities with different units must share a chart, give each its own axis and label both, and resist a third dataset. A chart with a clear question and one message beats a dashboard of decorations.

Colours and themes

Chart colours are strings in the model, so they do not follow the PrimeFaces theme automatically. Keep a small palette in one place, a utility class returning rgba(...) values, and use it everywhere so charts across the application look related. Choose colours with enough contrast against the background, and test the page in dark mode if your theme supports one, since a pale label on a pale bar disappears. Transparent fills on overlapping series let both stay visible.

Testing a chart bean

The bean is plain Java, so test the model without a browser. Build the chart for a known year with a stub SalesService, then assert that the labels have twelve entries, that the data has the same number and that the first value equals the stub's January total. That catches the two commonest chart bugs, misaligned lists and a changed grouping, in a unit test that runs in milliseconds.

Refreshing a chart without a full page update

For dashboards that refresh often, update only the chart component with update="chart" and avoid re-rendering the surrounding form. Keep the view-scoped bean small, because each chart model sits in the view state, and several large models per page add up. If a page holds many charts, load the heavy ones lazily when their tab or panel opens, using p:tabView with dynamic="true".

When to leave PrimeFaces charts

For highly custom visuals, use Chart.js or D3 directly: expose a JSON endpoint and call it from a p:remoteCommand, which gives you every Chart.js option instead of the subset the wrapper exposes. Documentation: the PrimeFaces chart showcase and the Chart.js documentation.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.