JSF PrimeFaces Guide to Maintaining JavaServer Faces Apps
Understand the Faces lifecycle, scopes, expression language and PrimeFaces components well enough to maintain and extend an existing application.

The Jakarta Faces specification and the PrimeFaces showcase are the primary sources here. There are a lot of JavaServer Faces applications still in production, many of them in banks, insurers and governments, and many of them maintained by people who inherited them. The framework behaves strangely until the lifecycle is clear, and then it behaves exactly as documented. This guide explains Jakarta Faces 4 and PrimeFaces well enough to maintain an application and to find the cause of the next odd error. The examples run on Jakarta EE 10 or newer with PrimeFaces on a recent servlet container.
If you are starting from zero, the JavaServer Faces tutorial for beginners builds a first page. For the platform around Faces, see what Jakarta EE is.
The lifecycle explains most bugs
Every Faces request passes through up to six phases:
| Phase | What happens | What breaks here |
|---|---|---|
| Restore view | The component tree is rebuilt or created | ViewExpiredException |
| Apply request values | Submitted values are copied onto components | Nothing, usually |
| Process validations | Converters and validators run | Validation errors skip to render |
| Update model values | Valid values are written into beans | Null in the expression path |
| Invoke application | Your action method runs | Never reached if validation failed |
| Render response | The page is produced | Anything bound to a bad property |
The classic puzzle, a button that does nothing, is a validation failure in phase three. The request jumps to render response, the action method never runs, and the only evidence is a message the page may not display. Add <h:messages /> or <p:messages /> during development and the page tells you. A fuller walk through is in JSF lifecycle phases explained.
Beans: use CDI
@Named
@ViewScoped
public class CustomerBean implements Serializable {
@Inject
private CustomerService service;
private String filter;
private List<Customer> customers;
@PostConstruct
void init() {
customers = service.findAll();
}
public void search() {
customers = service.search(filter);
}
public String getFilter() { return filter; }
public void setFilter(String filter) { this.filter = filter; }
public List<Customer> getCustomers() { return customers; }
}@Named makes the bean visible to expressions, and @ViewScoped (from jakarta.faces.view) keeps it alive while the user remains on the same view, then discards it. The bean must be Serializable, because the container may passivate it. The legacy @ManagedBean was deprecated in Faces 2.3 and removed in Faces 4.0, so a migration from old code starts here. Compare the two models in managed beans vs CDI beans.
Scopes decide how long state lives
| Scope | Lives for | Use it for |
|---|---|---|
@RequestScoped | One request | Read-only pages, simple actions |
@ViewScoped | One view, across AJAX calls | Forms and tables |
@SessionScoped | The user session | Login identity, preferences |
@ApplicationScoped | The application | Lookups shared by everyone |
Putting form state in session scope is the most common mistake: two browser tabs overwrite each other. Use view scope for forms. JSF bean scopes with examples shows the failure for each.
Facelets and expression language
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="jakarta.faces.html"
xmlns:f="jakarta.faces.core"
xmlns:p="http://primefaces.org/ui">
<h:head><title>Customers</title></h:head>
<h:body>
<h:form id="search">
<p:inputText id="filter" value="#{customerBean.filter}" />
<p:commandButton value="Search" action="#{customerBean.search}"
process="@form" update=":results" />
</h:form>
<p:dataTable id="results" value="#{customerBean.customers}" var="c">
<p:column headerText="Name"><h:outputText value="#{c.name}" /></p:column>
<p:column headerText="Email"><h:outputText value="#{c.email}" /></p:column>
</p:dataTable>
</h:body>
</html>The namespaces jakarta.faces.html and jakarta.faces.core are the Faces 4 form; Faces 3 and older used http://xmlns.jcp.org/jsf/html and /core. An application that mixes them fails to render components. The expression #{customerBean.filter} is a value binding: reading calls getFilter(), submitting calls setFilter(). If the path hits a null, you get Target Unreachable, identifier resolved to null. Read expression language and value binding for the resolution rules.
PrimeFaces: process and update
The two attributes you will use most are process, which names the components whose values are submitted and validated, and update, which names the components re-rendered afterwards. A button that fixes everything with update="@all" works and wastes bandwidth, and a button missing from process leaves a field unsubmitted. Reference by client id: :results with a leading colon means "from the root", which is needed when the target sits outside the current form.
Why a view expires
Faces stores view state in the session (the default) or in the client. When the session expires or the server restarts, the next postback cannot find its view and throws [ViewExpiredException](/library/viewexpiredexception-fix-javaserver-faces). Handle it with an error page that redirects to the login or the view, and consider whether a long form needs a longer session or a client-side state setting.
Finding a component: the id rules that cost everyone an afternoon
The update and process attributes take search expressions, and most "it did not refresh" bugs are a wrong expression. Faces gives each naming container (a h:form, a p:dataTable, a composite component) its own id scope, and the client id joins the ids with a colon. A field filter inside the form search has the client id search:filter. The rules in practice:
| Expression | Meaning |
|---|---|
@this | The component that fired the event |
@form | The enclosing form |
@parent | The parent component |
@namingcontainer | The closest enclosing naming container |
@all | The whole page |
results | A sibling or descendant id, found relative to the current naming container |
:results | A component found from the view root, even across forms |
:search:filter | An absolute client id |
A button inside the form search that updates a table outside the form must use :results, since a bare results is looked up inside search and fails with "Cannot find component with identifier". When in doubt, open the browser's developer tools, read the rendered id attribute and use it with a leading colon. The separator is configurable (jakarta.faces.SEPARATOR_CHAR), and changing it breaks every CSS selector and every piece of JavaScript that hard-coded the colon, so leave it alone.
Use process narrowly. A button that does not need the whole form, such as "cancel", should not submit and validate it:
<p:commandButton value="Cancel" action="#{customerBean.cancel}"
process="@this" update=":messages" immediate="true" />immediate="true" moves the action ahead of validation, so a cancel button does not fail because a required field is empty. Pair it with process="@this" or immediate alone can still leave you with surprising values.
A form with validation and conversion
Validation is where Faces earns its keep and where most maintenance questions start. Bean Validation annotations on the model are enforced by Faces in phase three, and messages come back to the page:
public class CustomerForm implements Serializable {
@NotBlank(message = "Name is required")
@Size(max = 80)
private String name;
@Email(message = "Enter a valid email address")
private String email;
@Min(value = 0, message = "Credit must not be negative")
private BigDecimal creditLimit;
// getters and setters
}<h:form id="edit">
<p:messages id="messages" showDetail="true" closable="true" />
<p:outputLabel for="name" value="Name" />
<p:inputText id="name" value="#{customerBean.form.name}" required="true" />
<p:outputLabel for="email" value="Email" />
<p:inputText id="email" value="#{customerBean.form.email}" />
<p:outputLabel for="credit" value="Credit limit" />
<p:inputNumber id="credit" value="#{customerBean.form.creditLimit}" decimalPlaces="2" />
<p:commandButton value="Save" action="#{customerBean.save}"
process="@form" update="@form" />
</h:form>A custom rule that spans no single annotation becomes a validator. It receives the submitted value and throws a ValidatorException with a message:
@FacesValidator("uniqueEmail")
public class UniqueEmailValidator implements Validator<String> {
@Inject
private CustomerService customers;
@Override
public void validate(FacesContext context, UIComponent component, String value) {
if (value != null && customers.emailExists(value)) {
throw new ValidatorException(new FacesMessage(
FacesMessage.SEVERITY_ERROR, "That email is already registered", null));
}
}
}Injection into a @FacesValidator works in Faces 4 on a CDI-enabled runtime, and fails with a NullPointerException on older setups where the validator is not a managed bean. If you see that, add managed="true" to the annotation, which is available from Faces 2.3, or register it as a CDI bean. A converter follows the same pattern and is needed whenever a component holds an object and the page holds a string, which is typical for a drop-down of entities:
@FacesConverter(forClass = Country.class, managed = true)
public class CountryConverter implements Converter<Country> {
@Inject
private CountryRepository countries;
@Override
public Country getAsObject(FacesContext context, UIComponent component, String value) {
return value == null || value.isBlank() ? null : countries.findByCode(value);
}
@Override
public String getAsString(FacesContext context, UIComponent component, Country value) {
return value == null ? "" : value.getCode();
}
}A "Validation Error: Value is not valid" on a select menu almost always means the converter or equals method of the entity is wrong, because Faces compares the submitted object with the available options before it accepts it.
A large table without loading it all: lazy data
p:dataTable with a plain list loads every row into the view. For anything over a few hundred rows, a lazy model asks your service for one page at a time and passes sorting and filtering through:
public class CustomerLazyModel extends LazyDataModel<Customer> {
private final CustomerService service;
public CustomerLazyModel(CustomerService service) {
this.service = service;
}
@Override
public int count(Map<String, FilterMeta> filterBy) {
return (int) service.count(toCriteria(filterBy));
}
@Override
public List<Customer> load(int first, int pageSize,
Map<String, SortMeta> sortBy, Map<String, FilterMeta> filterBy) {
return service.page(toCriteria(filterBy), toOrder(sortBy), first, pageSize);
}
@Override
public String getRowKey(Customer customer) {
return String.valueOf(customer.getId());
}
@Override
public Customer getRowData(String rowKey) {
return service.find(Long.valueOf(rowKey));
}
}<p:dataTable id="results" value="#{customerBean.model}" var="c" lazy="true"
paginator="true" rows="25" rowKey="#{c.id}" selectionMode="single"
selection="#{customerBean.selected}">
<p:column headerText="Name" sortBy="#{c.name}" filterBy="#{c.name}">
<h:outputText value="#{c.name}" />
</p:column>
</p:dataTable>Method signatures on LazyDataModel changed between PrimeFaces major versions, so match them to the version you run. The translation from FilterMeta and SortMeta to a query is the part to write carefully: build the where clause from an allow-list of column names, since the field names come from the browser, which is the same injection risk as in any other API.
Navigation: post, redirect, get
A button that returns a string navigates, and without a redirect the browser's address bar stays on the old URL and a refresh resubmits the form. Ask for a redirect and pass the data in the URL or the flash:
public String save() {
Customer saved = service.save(form.toCustomer());
FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "Saved " + saved.getName(), null));
return "customer?faces-redirect=true&id=" + saved.getId();
}The target page reads the id as a view parameter and loads the data with a view action, which runs in the invoke application phase, after the parameter has been converted and validated:
<f:metadata>
<f:viewParam name="id" value="#{customerView.id}" required="true" />
<f:viewAction action="#{customerView.load}" />
</f:metadata>This gives you bookmarkable URLs, which plain Faces navigation does not. The setKeepMessages(true) line carries the "Saved" message across the redirect, and without it the message is lost. Keep identifiers, not whole objects, in the URL, and load the object again on the other side.
Templates and composite components
Repeating the page chrome in every file is the first thing to remove from a growing application. A template defines the frame, and each page fills in the holes:
<!-- WEB-INF/templates/layout.xhtml -->
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="jakarta.faces.facelets"
xmlns:h="jakarta.faces.html">
<h:head><title><ui:insert name="title">Shop</ui:insert></title></h:head>
<h:body>
<ui:include src="/WEB-INF/templates/menu.xhtml" />
<ui:insert name="content" />
</h:body>
</ui:composition><!-- customers.xhtml -->
<ui:composition template="/WEB-INF/templates/layout.xhtml"
xmlns:ui="jakarta.faces.facelets"
xmlns:h="jakarta.faces.html">
<ui:define name="title">Customers</ui:define>
<ui:define name="content">
<h:outputText value="Customer list goes here" />
</ui:define>
</ui:composition>Templates under WEB-INF cannot be requested directly by a browser. For repeated fragments with their own parameters, such as a labelled input with its message, a composite component keeps the markup in one file and exposes attributes. A good test of whether to extract one is whether three pages carry the same twenty lines.
See the lifecycle with a phase listener
When a page misbehaves and the explanations are not enough, log the phases. A PhaseListener prints each phase boundary and any queued messages, and shows exactly where a request stopped:
public class TracingPhaseListener implements PhaseListener {
private static final Logger log = Logger.getLogger(TracingPhaseListener.class.getName());
@Override
public void beforePhase(PhaseEvent event) {
log.fine(() -> "BEFORE " + event.getPhaseId());
}
@Override
public void afterPhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
log.fine(() -> "AFTER " + event.getPhaseId()
+ " messages=" + context.getMessageList().size()
+ " renderResponse=" + context.getRenderResponse());
}
@Override
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
}<!-- WEB-INF/faces-config.xml -->
<faces-config xmlns="https://jakarta.ee/xml/ns/jakartaee" version="4.0">
<lifecycle>
<phase-listener>dev.javahacks.web.TracingPhaseListener</phase-listener>
</lifecycle>
</faces-config>A request that shows AFTER PROCESS_VALIDATIONS messages=1 renderResponse=true and then jumps to RENDER_RESPONSE is a validation failure, and the message list says why. Set the project stage to Development while debugging so that Faces prints more detail on the page, and to Production for deployment, which enables caching of the compiled view.
<context-param>
<param-name>jakarta.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>Session timeouts and view expiry, handled on purpose
The ViewExpiredException section earlier said what happens. A page that handles it gracefully takes three settings. A session timeout, an error page and a decision about where view state lives:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<error-page>
<exception-type>jakarta.faces.application.ViewExpiredException</exception-type>
<location>/expired.xhtml?faces-redirect=true</location>
</error-page>
<context-param>
<param-name>jakarta.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>Server-side state is the default and keeps the page small, with the cost of memory per view in each session. jakarta.faces.NUMBER_OF_VIEWS_IN_SESSION limits how many views one session keeps, which is why an old browser tab can fail after the user opened many new ones. Client-side state keeps nothing in the session and makes each request larger, which suits clusters without sticky sessions, provided the state is encrypted (Faces does this by default with a key from the container, and you should set an explicit, shared secret for a cluster so that every node can read another's state).
Upgrading to Faces 4 in a controlled order
Most maintenance work eventually becomes an upgrade, and the changes are mechanical when done in order:
- Move the runtime first. Choose a Jakarta EE 10 server such as WildFly, Payara or Open Liberty, or a servlet container with a Faces 4 implementation (Mojarra or MyFaces).
- Rename the packages:
javax.facesbecomesjakarta.faces, and so does every otherjavaximport. The namespace migration post covers the tooling. - Replace the XML namespaces in every
.xhtmlfile:http://xmlns.jcp.org/jsf/htmlbecomesjakarta.faces.html, and the others follow. A search-and-replace across the web folder does it. - Replace
@ManagedBeanand thejavax.faces.beanscopes with@Namedand the CDI scopes. - Upgrade PrimeFaces to a release built for Jakarta (the artifact has a
jakartaclassifier in some versions, check yours), and adjust the component calls that changed. - Deploy to a staging server, click through every page, and read the log for deprecation warnings.
Do the steps in separate commits, so that a regression has one suspect. An application that can be upgraded this way also becomes easier to hand to the next maintainer, and that is the real aim of a maintenance guide.
Performance in five habits
The slowness of a Faces page is almost always on the server, in what the beans do, and not in the component tree. These habits cover most of it:
- Load data in
@PostConstructor a view action, and never in a getter, since a getter can be called many times per request. AgetCustomers()that queries the database runs once per row of a table. - Use lazy loading for any table that can grow.
- Prefer
renderedon a component to hiding it with CSS, so that nothing is sent for what the user cannot see, and avoidui:includeinside largeui:repeatloops. - Narrow
processandupdateto the components that matter. - Keep session and view scope small: store ids and light objects, not entity graphs, because each active view is held in memory for each user.
Measure with the tools you have, such as the server's access log timings and a profiler on the one slow page, before you change anything. The slow part is, more often than not, one query repeated by a getter.
AJAX events on any component
Buttons are only one trigger. Any input can fire a request on an event and update part of the page, which is how dependent drop-downs and live validation are built. With the standard tag it reads like this:
<h:selectOneMenu id="country" value="#{addressBean.countryCode}">
<f:selectItems value="#{addressBean.countries}" var="c"
itemValue="#{c.code}" itemLabel="#{c.name}" />
<f:ajax event="valueChange" listener="#{addressBean.loadRegions}"
execute="@this" render="region" />
</h:selectOneMenu>
<h:selectOneMenu id="region" value="#{addressBean.regionCode}">
<f:selectItems value="#{addressBean.regions}" />
</h:selectOneMenu>execute is the standard attribute's name for what PrimeFaces calls process, and render is its update. PrimeFaces components usually bring their own p:ajax with the same ideas. Two details save time. Inputs inside the updated area are re-rendered from the bean, so the bean must hold the new state, which is why view scope matters for dependent fields. And a failed validation on the field that triggered the event stops the listener from running, which looks like the AJAX call "doing nothing". Check the messages component first, then the network tab for a response with an error element.
When a field should validate while the user types, delay the request, so that each keystroke does not send one:
<p:inputText id="email" value="#{customerBean.form.email}">
<p:ajax event="keyup" delay="500" process="@this" update="emailMessage" />
</p:inputText>
<p:message id="emailMessage" for="email" />Rendering untrusted text safely
Faces escapes output by default, so <h:outputText value="#{c.name}" /> shows a name containing a script tag as text. The way to lose that protection is escape="false", which is sometimes used to display formatted notes. Avoid it with user input, and if the content must contain markup, sanitize it when it is stored, as described in preventing XSS in Java web applications. Writing an expression straight into a page with no component, as in #{c.name} inside plain text, is escaped as well in Facelets, while the same text inside a <script> block is not safe from a JavaScript injection, so pass data to scripts through data- attributes or p:remoteCommand instead of concatenating it into script text.
Cross-site request forgery is handled for postbacks by the view state: a form submission must carry a valid jakarta.faces.ViewState for a view the session knows, and an attacker's page cannot supply it. Faces 4 protects navigation by GET with protected views, which limits a view to be reached only from another view in the same application:
<f:metadata>
<f:viewParam name="id" value="#{orderView.id}" />
</f:metadata><!-- WEB-INF/web.xml, or a faces-config entry, depending on the version -->
<protected-views>
<url-pattern>/admin/*</url-pattern>
</protected-views>Any action that changes data should be a postback, not a link with a query parameter. A GET that deletes a record can be triggered by an image tag on another site.
Uploading a file
A p:fileUpload in advanced mode posts files over AJAX and calls a listener per file, which suits attachments:
<h:form enctype="multipart/form-data">
<p:fileUpload listener="#{documentBean.upload}" mode="advanced"
allowTypes="/(\.|\/)(pdf|png|jpe?g)$/" sizeLimit="5242880"
update=":messages" />
</h:form>public void upload(FileUploadEvent event) throws IOException {
UploadedFile file = event.getFile();
String stored = UUID.randomUUID() + ".bin";
try (InputStream in = file.getInputStream()) {
Files.copy(in, storageDir.resolve(stored));
}
documents.save(new Document(stored, file.getFileName(), file.getContentType(), file.getSize()));
}The page restricts type and size, and the server must repeat both checks, because the browser's check is a convenience. The stored name is generated, never the user's, so a crafted filename cannot reach another directory, as covered in preventing path traversal.
Testing what you maintain
Faces pages are hard to test as a whole, so test at two levels. Put as much logic as you can into plain classes and services and test those with JUnit, with no container. A backing bean should be a thin layer that calls them. The bean itself can be checked with a mocked service:
class CustomerBeanTest {
@Test
void searchFiltersCustomers() {
CustomerService service = mock(CustomerService.class);
when(service.search("ana")).thenReturn(List.of(new Customer("Ana", "[email protected]")));
CustomerBean bean = new CustomerBean(service);
bean.setFilter("ana");
bean.search();
assertEquals(1, bean.getCustomers().size());
assertEquals("Ana", bean.getCustomers().get(0).getName());
}
}That test needs a constructor or a package-private setter for the service, which is a small change that makes the bean testable. For the pages, run a browser test against a deployed instance with Selenium or Playwright, limited to the paths that make money: log in, search, save, and one failing validation. A short browser suite that runs on every deployment beats a long one that nobody trusts, and it is the only test that catches a wrong update id, because that error exists only in the rendered page.
What to read next
A good order for a maintainer who has just inherited an application: first the lifecycle phases, then bean scopes, then the PrimeFaces showcase for the components the application already uses. Keep a list of the pages that break most often, since they point at a design problem in a scope or a getter, and fix the pattern, not the page.
Where Faces is the wrong tool
Faces fits form-heavy business applications maintained by a team that knows Java. It is not a good base for a public site that needs fast first paint on mobile, an API-first product or anything that wants a rich client-side experience. If you maintain one, you do not have to leave: a steady upgrade to Faces 4 on a current Jakarta EE runtime is a well-trodden path.


