2010-11-22

Getters called multiple times in JSF

In JSF, getters of your beans might be called multiple times per request - it’s a fact. Therefore making a data source call from the getter will have a negative impact on your performance.

Suppose you have a page with a form on it. The user fills and submits the form. There are two scenarios possible - submit success or failure. The expensive call could be acquiring a list of options to choose from on the form.

  1. The user opens the page.
  2. Make just one expensive database call. I.e. don’t make the same call twice.
  3. The user fills and submits the form.
  4. Display the success page, do not make the expensive database call.

  1. The user opens the page.
  2. Make just one expensive database call. I.e. don’t make the same call twice.
  3. The user fills and submits the form.
  4. Validation error occurs. Return to the form page and make the expensive call (to reload the list of options, for instance).

For these two scenarios putting the expensive database call in the constructor or getter will not work. You will either get too many calls or too few.

Solution


And here is the solution.

package me.m1key.sample.singlecall;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
// ...

@Named
@RequestScoped
public class UserBean {

   @Inject
   private FacesContext facesContext;

   public List<String> getUsernames() {
       if (facesContext.getRenderResponse()) {
           System.out.println("Expensive call...");
       }
       List<String> usernames = new ArrayList<String>();
       usernames.add("Michal");
       usernames.add("Ilinka");
       return usernames;
   }

This part does the trick:
if (facesContext.getRenderResponse()) {
   // Expensive stuff
}

Interested in how to inject FacesContext?

You can download sample code (a Maven app) that works on JBoss 6 M5.

25 comments:

  1. Thank you very much for this!
    Helped me a lot!

    ReplyDelete
  2. I went to your website and looked at the programming services you provide . I'm blown away by the services you offer since they're so unique. I would have absolutely used your services if they weren't so pricey in comparison to my budget. As a result, I believe I should compare it to other services in order to choose the finest Assignment Writing Service - Thedissertationhelp.co.uk within my budget.

    ReplyDelete
  3. Most of you often put a search query as ‘who can make my assignment for me at a cheap rate in the UK?’ Here we are, offering the best service at a reasonable price.

    ReplyDelete
  4. Hasten Contracting possesses the expertise and know-how required to plan and construct CEMENT TREATED BASEpavements that are particular to the demands and requirements of each project. We collaborate closely with our clients to guarantee that the final product is of the highest quality and conforms with all applicable standards and laws.

    ReplyDelete
  5. Our company exclusively works with the most devoted, knowledgeable, and motivated optimizers while providingSearch engine optimization dubaiUnited Arab Emirates, is home to our corporate headquarters. Since we believe that every website should be an absolute delight to use, we are dedicated to directing traffic to websites that are aesthetically beautiful, practical, and simple to use.

    ReplyDelete
  6. Our exclusive design combines the strength and durability of a pump with the speed and efficiency of an electric one. In fact, it only takes half as long to transfer liquids as it does with manualhydrocarbon pumps Aberdeen pumps! And because our system is lightweight, you can use it for any kind of application. So think about switching to combinedpump today - you won't regret it!

    ReplyDelete
  7. As a developer, it's important to be mindful of the performance impact of your code, especially in JSF where getters can be called multiple times per request. By avoiding making data source calls from getters, you can improve the overall performance of your application.In terms of lighting solutions, it's important to use high-quality electrical lighting in Dubai to ensure a safe and efficient working environment. With a range of options available from reputableelectrical lighting dubai, it's easy to find the right lighting solution to meet your needs.



    ReplyDelete

  8. I Valuable information for your blog. Thanks for giving me the wonderful opportunity to read this valuable article.
    Bankruptcy near me attorney

    ReplyDelete
  9. The getters are called multiple times in JSF, as they are used to provide a default value for properties. The getters are also useful when you need to create a new instance of an object but do not know the class name. Introduction: In Java, the getters and setters can be used to make code more readable. For instance, if we have an object of type Person, we might want to make it easier for other developers on the team to understand what properties they can change by using getter and setter methods. Most students are drawn to these types of articles and information, but they are unable to prepare for their exams, If you have been struggling with your exams and want assistance, students can hire someone to take my online class and get higher grades on their examinations by providing them with the best available resources, including quality academic services.

    ReplyDelete
  10. The custom iOS app development company is a true gem in the industry. Their dedication to crafting tailor-made apps for Apple devices sets them apart, delivering seamless and engaging user experiences.

    ReplyDelete
  11. This blog on calling getters multiple times in JSF is extremely helpful! It provides valuable insights on optimizing performance. By the way, if you're looking to optimize your expenses while shopping online, don't forget to check out "UsePromos" for exclusive deals and discounts. A great combination of programming tips and smart savings opportunities!

    ReplyDelete
  12. While take my online class can be convenient, it also comes with its own set of challenges. One of the common challenges faced by students is managing their time effectively to balance their academic commitments with other responsibilities. This is where hiring a professional to take your online class for you can be a game-changer.

    ReplyDelete
  13. Your blog has become a valuable part of my online routine. Your clarity and depth of thought in each article are truly commendable.Prevención Violencia Doméstica Acto Nueva Jersey

    ReplyDelete

  14. Experiencing multiple calls to getters in JSF can sometimes lead to inefficiencies and performance issues in your web application. It's essential to optimize your code to ensure smooth user experiences. And just like maintaining code, keeping your car clean is crucial too. If you're in Ottawa, Canada, and need a professional car wash service, considerCar Wash Ottawa to keep your vehicle looking its best while you focus on your coding challenges.

    ReplyDelete
  15. Getters called multiple times in JSF highlights a common programming challenge. Just as you seek efficient solutions in coding, ensure that your Remote-site catering services in Houston Texas receive efficient and satisfying meals with Remote-Site Catering Services. It's all about optimizing performance, whether in software or on the job site.

    ReplyDelete
  16. Getters called multiple times in JSF" explores a technical aspect of web development. Similarly, the Best Barber Shop in Canadafocuses on the finer details, providing top-notch grooming services that leave customers looking and feeling their best.

    ReplyDelete
  17. Encountering multiple calls to getters in JSF? Ensure a seamless user experience by addressing this issue promptly. For robust chain link fencing Edmonton, consider our reliable chain link fencing services that prioritize both security and aesthetics.

    ReplyDelete
  18. While multiple calls to getter methods in JavaServer Faces (JSF) can sometimes be perceived as a challenge, there are potential advantages to this behavior within the context of JSF applications.Thank You For The Blog.
    uncontested divorce virginia beach

    ReplyDelete
  19. JavaServer Faces (JSF) is a powerful technology for building web applications, but it's important to be mindful of its performance characteristics. In particular, JSF's getters can be a source of performance issues if called multiple times per request. To prevent validation errors and enhance overall efficiency, it's strongly recommended to make only one expensive database call within a request cycle.

    While this advice is essential for improving your JSF application's performance, it's worth noting that there are also other situations where optimization is key. If you're looking for ways to enhance your reflective essay writing service uk, these principles of efficiency can be applied as well. By understanding how to minimize getter calls in JSF, you'll not only create a more responsive web application but also improve the quality of your services in the academic writing field.

    ReplyDelete
  20. Your blog about Getters called multiple times in JSF is stands out as a beacon of knowledge and inspiration. Your commitment to sharing valuable insights is evident in every post. I'm continually impressed by the depth and relevance of your content. Thank you for being a reliable source of enlightenment. New York Divorce Waiting Period New York Divorce No Fault

    ReplyDelete
  21. Addressing the challenge of multiple calls to Getters in JSF – a quest for efficiency and optimal performance! And for those in Ottawa, ensure your vehicles receive the same level of attention with Car Wash Ottawa in services. Because just like streamlined code, a well-detailed car adds a touch of excellence to your daily drive! #JSFProgramming #OttawaCarCare #EfficiencyMatters #CarWashExcellence

    ReplyDelete
  22. "Important insight into JSF performance optimization! Avoid costly database calls in getters for optimal efficiency, ensuring a balance between data retrieval and user experience. Well-explained scenarios provide a clear guide for developers."

    Impugnado Divorcio Estado de Nueva York

    ReplyDelete
  23. The JavaServer Faces framework may experience performance issues due to multiple getter calls, requiring optimization and careful coding practices to minimize unnecessary calls and enhance application efficiency. Preliminary Conference Divorce New York

    ReplyDelete
  24. JavaServer Faces (JSF), a web application framework for building user interfaces, the issue of getters being called multiple times often arises due to the lifecycle of JSF components. JSF components, including managed beans, undergo a series of phases such as restore view, apply request values, process validations, and more during each HTTP request. Getters for properties bound to the user interface components may be invoked multiple times as the framework navigates through these phases. This behavior can be unexpected for developers and may lead to performance concerns, especially if the getter methods involve complex or resource-intensive operations.
    lawyer for motorcycle accident
    virginia personal injury lawyer

    ReplyDelete
  25. Solving the JSF problem of multiple calls to getters—a frequently asked question in the programming community! Efficient code execution requires resolving these complexities. Comparably,Industry Leading Degassing Solution tackles intricacies in the environmental domain, effectively reducing possible risks and guaranteeing a safer, cleaner atmosphere.

    ReplyDelete