DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • User Authentication With Amazon Cognito
  • Attribute-Level Governance Using Apache Iceberg Tables
  • Integrating Redis With Message Brokers
  • Terraform State File: Key Challenges and Solutions

Trending

  • Setting Up Data Pipelines With Snowflake Dynamic Tables
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Why I Started Using Dependency Injection in Python
  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]

JSF and the "immediate" Attribute - Command Components

By 
Jeremiah Orr user avatar
Jeremiah Orr
·
Jun. 19, 12 · Interview
Likes (4)
Comment
Save
Tweet
Share
28.4K Views

Join the DZone community and get the full member experience.

Join For Free
The immediate attribute in JSF is commonly misunderstood. If you don't believe me, check out Stack Overflow. Part of the confusion is likely due to immediate being available on both input (i.e.. <h:inputText />) and command (i.e. <h:commandButton />) components, each of which affects the JSF lifecycle differently.

Here is the standard JSF lifecycle:


For the purposes of this article, I'll assume you are familiar with the basics of the JSF lifecycle. If you need an introduction or a memory refresher, check out the Java EE 6 Tutorial - The Lifecycle of a JavaServer Faces Application.

Note: the code examples in this article are for JSF 2 (Java EE 6), but the principals are the same for JSF 1.2 (Java EE 5).

immediate=true on Command components

In the standard JSF lifecycle, the action attribute on an Command component is evaluated in the Invoke Application phase. For example, say we have a User entity/bean:

 

public class User implements Serializable {

 @NotBlank
 @Length(max = 50)
 private String firstName;

 @NotBlank
 @Length(max = 50)
 private String lastName;

 /* Snip constructors, getters/setters, a nice toString() method, etc */
}

And a UserManager to serve as our managed bean:

@SessionScoped
@ManagedBean
public class UserManager {
 private User newUser;

 /* Snip some general page logic... */

 public String addUser() {
  //Snip logic to persist newUser

  FacesContext.getCurrentInstance().addMessage(null,
    new FacesMessage("User " + newUser.toString() + " added"));

  return "/home.xhtml";
 }

And a basic Facelets page, newUser.xhtml, to render the view:

<h:form>
 <h:panelGrid columns="2">

  <h:outputText value="First Name: " />
  <h:panelGroup>
   <h:inputText id="firstName"
    value="#{userManager.newUser.firstName}" />
   <h:message for="firstName" />
  </h:panelGroup>

  <h:outputText value="Last Name: " />
  <h:panelGroup>
   <h:inputText id="lastName" value="#{userManager.newUser.lastName}" />
   <h:message for="lastName" />
  </h:panelGroup>

 </h:panelGrid>

 <h:commandButton value="Add User" action="#{userManager.addUser()}" />
</h:form>

Which all combine to produce this lovely form:


When the user clicks on the Add User button, #{userManager.addUser} will be called in the Invoke Application phase; this makes sense, because we want the input fields to be validated, converted, and applied to newUser before it is persisted.

Now let's add a "cancel" button to the page, in case the user changes his/her mind. We'll add another <h:commandButton /> to the page:

<h:form>
 <!-- Snip Input components --> 

 <h:commandButton value="Add User" action="#{userManager.addUser()}" />
 <h:commandButton value="Cancel" action="#{userManager.cancel()}" />
</h:form>

And the cancel() method to UserManager:

public String cancel() {
 newUser = new User();

 FacesContext.getCurrentInstance().addMessage(null,
   new FacesMessage("Cancelled new user"));

 return "/home.xhtml";
}

Looks good, right? But when we actually try to use the cancel button, we get errors complaining that first and last name are required:


This is because #{userManager.cancel} isn't called until the Invoke Application phase, which occurs after the Process Validations phase; since we didn't enter a first and last name, the validations failed before #{userManager.cancel} is called, and the response is rendered after the Process Validations phase.

We certainly don't want to require the end user to enter a valid user before cancelling! Fortunately, JSF provides the immediate attribute on Command components. When immediate is set to true on an Command component, the action is invoked in the Apply Request Values phase:


This is perfect for our Cancel use case. If we add immediate=true to the Cancel , #{userManager.cancel} will be called in the Apply Request Values phase, before any validation occurs.

<h:form>  
 <!-- Snip Input components -->

 <h:commandButton value="Add User" action="#{userManager.addUser()}" />
 <h:commandButton value="Cancel" action="#{userManager.cancel()}" immediate="true" />
</h:form>

So now when we click cancel, #{userManager.cancel} is called in the Apply Request Values phase, and we are directed back to the home page with the expected cancellation message; no validation errors!



What about Input components?

Input components have the immediate attribute as well, which also moves all their logic into the Apply Request Values phase. However, the behavior is slightly different from Command components, especially depending on whether or not the validation on the Input component succeeds. My next article will address immediate=true on Input components. For now, here's a preview of how the JSF lifecycle is affected:




 

 

 

 

Command (computing) Attribute (computing)

Published at DZone with permission of Jeremiah Orr, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • User Authentication With Amazon Cognito
  • Attribute-Level Governance Using Apache Iceberg Tables
  • Integrating Redis With Message Brokers
  • Terraform State File: Key Challenges and Solutions

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!