App running with JSF, Primefaces, eclipselink, not a small app, about 100 pages/bean all working perfectly
I got some troubles understanding how my #ViewScoped page works, I got a select UI component, filled with a simple List<People> and a back-end selectedPeople in my bean
// all getters, setters, JPA annotations, all good
public class People {
private String name;
private List<Car> cars;
}
#ManagedBean
#ViewScoped
public class PeopleBean {
#EJB
private Service sPeople;
private People selectedPeople;
private List<People> listPpl;
#PostConstruct
public void init(){
listPpl = sPeople.readAll(); // always good, same as DB values
}
public People getSelectedPeople(){
return selectedPeople;
}
public People setSelectedPeople(People p){ // p is an old element
selectedPeople = p; // BREAKPOINT
}
// getter for the list too
public void method(){
Logger.getAnoymousLogger().severe(selectedPeople.getCars()); // the one the old people, not the ne contained in the actual list
}
}
<p:selectOneMenu id="selectP" value="#{peopleBean.selectedPeople}" converted="#{genericSecuerdConverter}" >
<p:ajax event="change" partialSubmit="true" listener="#{peopleBean.method()}" />
<f:selectItems value="#{peopleBean.listPpl}" var="people" itemLabel="#{people.name}" itemValue="#{people}" />
</p:selectOneMenu>
Sequence of use and problem is (information taken from debugging) :
go to peoplePage.xhtml where the select element is, IDs of the list's element are #410, #411, #412 (3 peoples)
go to modif.xhtml, change the 3rd people (remove a car, saved in DB (check in DB))
come back to peoplePage.xhtml, list is OK, IDs in debug are #650, #651, #652
change the value (from null) of the selectUI to choose a people, and at the breakpoint, p appears to be the #412 element, so the changes on its car's list are not visible, it does not come from the listPpl (because contains only valid elements and corresponds to DB), it's kind of caching
I tried to disable ecpliselink cache as states EclipleLink cache
change eclipselink property
change JPA propery
use #Cacheable(false)
No one had an effect, nor go to private navigation neither clear the browser cache and come back to the page, the p element is still the old one from first loading
I thought #ViewScoped allows to open a page each time as if it was the first time, but seems not, can't figure where the element can be stored/cached
Edit I used a workaround for the moment but this is obviously o the best solution
public People setSelectedPeople(People p){
if(p!=null)
selectedPeople = sPeople.read(p.getId());
}
What you are looking for is #RequestScoped. It will create everything each and every time you do a suitable HTTP request. Otherwise it is not guaranteed to destroy the #ViewScoped beans. An example in the Omnifaces documentation: ViewScoped.
This feature could be used to help the recreation of the page when the user is using the back and forward buttons of the browser for example.
#RequestScoped
Bean lives as long as the HTTP request-response lives. It gets created upon a HTTP request and gets destroyed when the HTTP response associated with the HTTP request is finished.
#ViewScoped
Bean lives as long as the user is interacting with the same JSF view in the browser window/tab. It gets created upon a HTTP request and gets destroyed once the user postbacks to a different view.
Source of descriptions: https://www.tutorialspoint.com/jsf/jsf_managed_beans.htm
Related
Let's say I specify an outputText component like this:
<h:outputText value="#{ManagedBean.someProperty}"/>
If I print a log message when the getter for someProperty is called and load the page, it is trivial to notice that the getter is being called more than once per request (twice or three times is what happened in my case):
DEBUG 2010-01-18 23:31:40,104 (ManagedBean.java:13) - Getting some property
DEBUG 2010-01-18 23:31:40,104 (ManagedBean.java:13) - Getting some property
If the value of someProperty is expensive to calculate, this can potentially be a problem.
I googled a bit and figured this is a known issue. One workaround was to include a check and see if it had already been calculated:
private String someProperty;
public String getSomeProperty() {
if (this.someProperty == null) {
this.someProperty = this.calculatePropertyValue();
}
return this.someProperty;
}
The main problem with this is that you get loads of boilerplate code, not to mention private variables that you might not need.
What are the alternatives to this approach? Is there a way to achieve this without so much unnecessary code? Is there a way to stop JSF from behaving in this way?
Thanks for your input!
This is caused by the nature of deferred expressions #{} (note that "legacy" standard expressions ${} behave exactly the same when Facelets is used instead of JSP). The deferred expression is not immediately evaluated, but created as a ValueExpression object and the getter method behind the expression is executed everytime when the code calls ValueExpression#getValue().
This will normally be invoked one or two times per JSF request-response cycle, depending on whether the component is an input or output component (learn it here). However, this count can get up (much) higher when used in iterating JSF components (such as <h:dataTable> and <ui:repeat>), or here and there in a boolean expression like the rendered attribute. JSF (specifically, EL) won't cache the evaluated result of the EL expression at all as it may return different values on each call (for example, when it's dependent on the currently iterated datatable row).
Evaluating an EL expression and invoking a getter method is a very cheap operation, so you should generally not worry about this at all. However, the story changes when you're performing expensive DB/business logic in the getter method for some reason. This would be re-executed everytime!
Getter methods in JSF backing beans should be designed that way that they solely return the already-prepared property and nothing more, exactly as per the Javabeans specification. They should not do any expensive DB/business logic at all. For that the bean's #PostConstruct and/or (action)listener methods should be used. They are executed only once at some point of request-based JSF lifecycle and that's exactly what you want.
Here is a summary of all different right ways to preset/load a property.
public class Bean {
private SomeObject someProperty;
#PostConstruct
public void init() {
// In #PostConstruct (will be invoked immediately after construction and dependency/property injection).
someProperty = loadSomeProperty();
}
public void onload() {
// Or in GET action method (e.g. <f:viewAction action>).
someProperty = loadSomeProperty();
}
public void preRender(ComponentSystemEvent event) {
// Or in some SystemEvent method (e.g. <f:event type="preRenderView">).
someProperty = loadSomeProperty();
}
public void change(ValueChangeEvent event) {
// Or in some FacesEvent method (e.g. <h:inputXxx valueChangeListener>).
someProperty = loadSomeProperty();
}
public void ajaxListener(AjaxBehaviorEvent event) {
// Or in some BehaviorEvent method (e.g. <f:ajax listener>).
someProperty = loadSomeProperty();
}
public void actionListener(ActionEvent event) {
// Or in some ActionEvent method (e.g. <h:commandXxx actionListener>).
someProperty = loadSomeProperty();
}
public String submit() {
// Or in POST action method (e.g. <h:commandXxx action>).
someProperty = loadSomeProperty();
return "outcome";
}
public SomeObject getSomeProperty() {
// Just keep getter untouched. It isn't intented to do business logic!
return someProperty;
}
}
Note that you should not use bean's constructor or initialization block for the job because it may be invoked multiple times if you're using a bean management framework which uses proxies, such as CDI.
If there are for you really no other ways, due to some restrictive design requirements, then you should introduce lazy loading inside the getter method. I.e. if the property is null, then load and assign it to the property, else return it.
public SomeObject getSomeProperty() {
// If there are really no other ways, introduce lazy loading.
if (someProperty == null) {
someProperty = loadSomeProperty();
}
return someProperty;
}
This way the expensive DB/business logic won't unnecessarily be executed on every single getter call.
See also:
Why is the getter called so many times by the rendered attribute?
Invoke JSF managed bean action on page load
How and when should I load the model from database for h:dataTable
How to populate options of h:selectOneMenu from database?
Display dynamic image from database with p:graphicImage and StreamedContent
Defining and reusing an EL variable in JSF page
Measure the render time of a JSF view after a server request
With JSF 2.0 you can attach a listener to a system event
<h:outputText value="#{ManagedBean.someProperty}">
<f:event type="preRenderView" listener="#{ManagedBean.loadSomeProperty}" />
</h:outputText>
Alternatively you can enclose the JSF page in an f:view tag
<f:view>
<f:event type="preRenderView" listener="#{ManagedBean.loadSomeProperty}" />
.. jsf page here...
<f:view>
I have written an article about how to cache JSF beans getter with Spring AOP.
I create a simple MethodInterceptor which intercepts all methods annotated with a special annotation:
public class CacheAdvice implements MethodInterceptor {
private static Logger logger = LoggerFactory.getLogger(CacheAdvice.class);
#Autowired
private CacheService cacheService;
#Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String key = methodInvocation.getThis() + methodInvocation.getMethod().getName();
String thread = Thread.currentThread().getName();
Object cachedValue = cacheService.getData(thread , key);
if (cachedValue == null){
cachedValue = methodInvocation.proceed();
cacheService.cacheData(thread , key , cachedValue);
logger.debug("Cache miss " + thread + " " + key);
}
else{
logger.debug("Cached hit " + thread + " " + key);
}
return cachedValue;
}
public CacheService getCacheService() {
return cacheService;
}
public void setCacheService(CacheService cacheService) {
this.cacheService = cacheService;
}
}
This interceptor is used in a spring configuration file:
<bean id="advisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="pointcut">
<bean class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut">
<constructor-arg index="0" name="classAnnotationType" type="java.lang.Class">
<null/>
</constructor-arg>
<constructor-arg index="1" value="com._4dconcept.docAdvance.jsfCache.annotation.Cacheable" name="methodAnnotationType" type="java.lang.Class"/>
</bean>
</property>
<property name="advice">
<bean class="com._4dconcept.docAdvance.jsfCache.CacheAdvice"/>
</property>
</bean>
Hope it will help!
Originally posted in PrimeFaces forum # http://forum.primefaces.org/viewtopic.php?f=3&t=29546
Recently, I have been obsessed evaluating the performance of my app, tuning JPA queries, replacing dynamic SQL queries with named queries, and just this morning, I recognized that a getter method was more of a HOT SPOT in Java Visual VM than the rest of my code (or majority of my code).
Getter method:
PageNavigationController.getGmapsAutoComplete()
Referenced by ui:include in in index.xhtml
Below, you will see that PageNavigationController.getGmapsAutoComplete() is a HOT SPOT (performance issue) in Java Visual VM. If you look further down, on the screen capture, you will see that getLazyModel(), PrimeFaces lazy datatable getter method, is a hot spot too, only when enduser is doing a lot of 'lazy datatable' type of stuff/operations/tasks in the app. :)
See (original) code below.
public Boolean getGmapsAutoComplete() {
switch (page) {
case "/orders/pf_Add.xhtml":
case "/orders/pf_Edit.xhtml":
case "/orders/pf_EditDriverVehicles.xhtml":
gmapsAutoComplete = true;
break;
default:
gmapsAutoComplete = false;
break;
}
return gmapsAutoComplete;
}
Referenced by the following in index.xhtml:
<h:head>
<ui:include src="#{pageNavigationController.gmapsAutoComplete ? '/head_gmapsAutoComplete.xhtml' : (pageNavigationController.gmaps ? '/head_gmaps.xhtml' : '/head_default.xhtml')}"/>
</h:head>
Solution: since this is a 'getter' method, move code and assign value to gmapsAutoComplete prior to method being called; see code below.
/*
* 2013-04-06 moved switch {...} to updateGmapsAutoComplete()
* because performance = 115ms (hot spot) while
* navigating through web app
*/
public Boolean getGmapsAutoComplete() {
return gmapsAutoComplete;
}
/*
* ALWAYS call this method after "page = ..."
*/
private void updateGmapsAutoComplete() {
switch (page) {
case "/orders/pf_Add.xhtml":
case "/orders/pf_Edit.xhtml":
case "/orders/pf_EditDriverVehicles.xhtml":
gmapsAutoComplete = true;
break;
default:
gmapsAutoComplete = false;
break;
}
}
Test results: PageNavigationController.getGmapsAutoComplete() is no longer a HOT SPOT in Java Visual VM (doesn't even show up anymore)
Sharing this topic, since many of the expert users have advised junior JSF developers to NOT add code in 'getter' methods. :)
If you are using CDI, you can use Producers methods.
It will be called many times, but the result of first call is cached in scope of the bean and is efficient for getters that are computing or initializing heavy objects!
See here, for more info.
You could probably use AOP to create some sort of Aspect that cached the results of our getters for a configurable amount of time. This would prevent you from needing to copy-and-paste boilerplate code in dozens of accessors.
If the value of someProperty is
expensive to calculate, this can
potentially be a problem.
This is what we call a premature optimization. In the rare case that a profiler tells you that the calculation of a property is so extraordinarily expensive that calling it three times rather than once has a significant performance impact, you add caching as you describe. But unless you do something really stupid like factoring primes or accessing a databse in a getter, your code most likely has a dozen worse inefficiencies in places you've never thought about.
I would also advice using such Framework as Primefaces instead of stock JSF, they address such issues before JSF team e. g in primefaces you can set partial submit. Otherwise BalusC has explained it well.
It still big problem in JSF. Fo example if you have a method isPermittedToBlaBla for security checks and in your view you have rendered="#{bean.isPermittedToBlaBla} then the method will be called multiple times.
The security check could be complicated e.g . LDAP query etc. So you must avoid that with
Boolean isAllowed = null ... if(isAllowed==null){...} return isAllowed?
and you must ensure within a session bean this per request.
Ich think JSF must implement here some extensions to avoid multiple calls (e.g annotation #Phase(RENDER_RESPONSE) calle this method only once after RENDER_RESPONSE phase...)
I use Java Server Faces and I have some beans. In my xhtml page, I display some drop down lists with the latest selected value at the top. I would like to know how to reinitialize the values when I quit the page (but not the session, by example, by clicking on another page of my web site) and come back to the first page), so that when I come back, my drop down list has the by default value at the top, not the selected one before I quit the page.
Should I put something in the bean constructor ?
The structure of the bean is
#ManagedBean(name = "myBean", eager = true)
#SessionScoped
public class myBean implements Serializable {
....
public myBean () {
...
}
}
You can use onLoad function
<h:body onload="#{app.initilize()}">
where the code goes
#ManagedBean(name = "app", eager = true)
#SessionScoped
public class MyApp {
public void initilize() {
....
}
Since your bean is #SessionScoped, it will only be instantiated once in the session. So, the constructor will be called once.
Use the value from a #RequestScoped or #ViewScoped bean, or set the value in your bean through the controller.
Do not forget to follow Java naming conventions (all classes names begin with uppercase).
I think the scope which applies more suitable to your bean is #RequestScoped (see http://docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html).
On PAGE A is a table with some data from the database.
by clicking on a row, the page will be forwarded to PAGE B and in the controller the entity will be injected
#DataModelSelection(value = ENTITY_LIST_NAME)
#Out(value = ENTITY_NAME, scope = ScopeType.CONVERSATION, required = false)
private Entity entity;
this works as it should.
The problem is, that our users seems to use bookmark for PAGE B, so the entity will never be injected because they never visited PAGE A
so they always throw this exception
#In attribute requires non-null value
Is there a global function to catch all #In attribute requires non-null value exceptions and forward the user to PAGE C (startpage)?
(of course i can catch this execption on PAGE B but this happens not only on one page, we want to handle this exception on every page)
we are using: jboss5 + jsf 1.2 + seam 2
UPDATE after the answer of EmirCalabuch:
I also tried the hint from EmirCalabuch with:
<page conversation-required="true" no-conversation-view-id="PageC.xhtml" />
but the problem is, that the conversation is alive at this moment, to this forwarding to pageC never happens...
i also made in the page.xml of this page something like:
<action execute="#{controller.checkIfEntityIsSet()}" />
<navigation>
<rule if-outcome="HOME">
<redirect
view-id="/pages/home.xhtml"
/>
</rule>
</navigation>
and in my Controller.java i have somthing like this:
public String checkIfEntityIsSet(){
if(getEntity() == null){
return "HOME";
}
return "";
}
but this checkIfEntityIsSet() is never called, because the #In attribute requires non-null value is thrown before... so this was not a help at all...
Exception handling rules are specified in pages.xml. You could include a rule to catch the org.jboss.seam.RequiredException that is thrown for that type of error and perform your navigation to page C in it.
This however is not a very clean solution as you would bind that exception to that page and most probably you will have this exception elsewhere and would like to redirect to a different page.
A simpler way of achieving the same result is making the conversation required in PageB.page.xml and specifying the view to redirect to when no conversation is active. The page descriptor has an option that allows you to do just that (on PageB.page.xml):
<page conversation-required="true" no-conversation-view-id="PageC.xhtml" />
This tells Seam that if a user tries to display page B and there is no conversation active (which happens when the user gets there from a bookmark), then redirect the user to PageC.xhtml.
Anyway, it takes very little effort to make the page bookmarkable (if you feel your users will be bookmarking it a lot), using page parameters and actions, for example:
In your list page A, instead of an h:commandLink or h:commandButton for each of the rows that take you to page B, use s:link or s:button:
<h:dataTable var="var" value="#{myList.dataModel}">
...
<s:link value="PageB.xhtml">
<f:param name="id" value="#{var.id}" />
</s:link>
...
</h:dataTable>
This will create a link to Page B for each of the entities in the list, passing its ID (for example, PageB.seam?id=1 in the first row, PageB.seam?id=2 in the second and so on. These links are bookmarkable.
On PageB.page.xml declare the parameter:
<param name="id" value="#{myHomeComponent.id}" />
Where myHomeComponent is a component of type EntityHome<YourEntity>. You can then use #{myHomeComponent.instance} inside Page B to access the entity selected.
i managed it now different:
in the Controller.java i have for the initialization something like this:
#Create
public void initialize() throws MissingMyEntityException {
if(qualifiedCustomer == null){
throw new MissingMyEntityException("something wrong");
}
....
}
my MissingMyEntityException.java looks like this:
public class MissingMyEntityException extends Exception {
private static final long serialVersionUID = 8640645441429393157L;
public MissingMyEntityException(String message) {
super(message);
}
}
and in the pages.xml i have the exception handler like this:
<exception class="com.dw.companyName.view.xyz.exception.MissingMyEntityException">
<redirect view-id="/pages/home.xhtml">
<message>something went wrong</message>
</redirect>
</exception>
and this fixed the problem.
but thanks for your help, but it was not working your way :(
I would like to write my business logic after the getters and setters are called (twice),
because I use their object values inside the business logic.
However Construct, Post construct, actionevents,.. are called before the getters.
So how can I use the values of the getters if I don't want to write business logic inside them?
I want to navigate to the site and get data from a database displayed into outputText.
Do the job in (post)constructor of the bean.
#ManagedBean
#RequestScoped
public class Bean {
private String data;
#EJB
private SomeService service;
#PostConstruct
public void init() {
data = service.load();
}
// Getter.
}
with
<h:outputText value="#{bean.data}" />
When I change a (primefaces)selectOneMenu value the bean gets the selectOneMenu's value and performs a query in the database for this value, and writes the query result inside the outputText.
Do the job in the ajax listener method of the bean which is attached to input component's change event.
#ManagedBean
#ViewScoped
public class Bean {
private String selectedItem;
private String result;
#EJB
private SomeService service;
public void changeSelectedItem(AjaxBehaviorEvent event) {
result = service.find(selectedItem);
}
// Getters+setter.
}
with
<p:selectOneMenu value="#{bean.selectedItem}">
<f:selectItems ... />
<p:ajax listener="#{bean.changeSelectedItem}" update="result" />
</p:selectOneMenu>
<h:outputText id="result" value="#{bean.result}" />
Doing it after the getters are called would be too late. JSF would at that point already be finished with rendering the HTML output. You can't change the HTML output afterwards.
You are making a basic mistake in your thinking.
There is no such phase as "The Getters". Getters are just a convention to read a property of a bean.
Those properties can be read individually throughout the entire request. Some may be consulted as early as during "create/restore view", while others may be consulted during "render response".
There is no such thing as that JSF in one particular phase does a sweep through your code and for the fun of it calls every getter it finds.
The solution for you is to let this thinking go. I know it might be hard to let go of something you think is true, but inhale, clear you mind, say goodbye to your current understanding of how things work, and just re-learn from scratch.
You'll then find the answer yourself in no-time. Good luck!
Did not understand your question fully, but obvious way is to put logic in getters and setters.
I have to warn you: the question may be rather silly, but I can't seem to wrap my head around it right now.
I have two managed beans, let's say A and B:
class A
{
private Date d8; // ...getters & setters
public String search()
{
// search by d8
}
}
class B
{
private Date d9; //...getters & setters
public String insert()
{
// insert a new item for date d9
}
}
and then I have two JSP pages, pageA.jsp (the search page) and pageB.jsp (the input page).
What I would like to do is placing a commandbutton in pageB so to open the search page pageA passing the parameter d9 somehow, or navigating to pageA directly after b.insert(). What I would like to do is showing the search result after the insertion.
Maybe it's just that I can't see the clear, simple solution, but I'd like to know what the best practice might be here, also...
I though of these possible solutions:
including **A** in **B** and linking the command button with **b.a.search**
passing **d9** as a **hiddenInput** and adding a new method **searchFromB** in **A** (ugly!)
collapsing the two beans into one
JSF 1.1/1.2 raw doesn't provide an easy way to do this. Seam/Spring both have ways around this and there are a couple of things you can do. JSF 2 should also have solutions to this once it is released.
Probably the easiest and most expedient would be to collapse the two beans into one and make it session scoped. The worry, of course, is that this bean will not get removed and stay in session until the session times out. Yay Memory leaks!
The other solution would be to pass the date on as a GET parameter. For instance, you action method could call the
FacesContext.getCurrentInstance().getExternalContext().redirect("pageB?d9=" + convertDateToLong(d9));
and then get the parameter on the other side.
You should configure the navigation flow in faces-config.xml. In ideal scenario you would return a "status" message which would decide the flow. Read more at following link:
http://www.horstmann.com/corejsf/faces-config.html
http://publib.boulder.ibm.com/infocenter/rtnlhelp/v6r0m0/index.jsp?topic=/com.businessobjects.integration.eclipse.doc.devtools/developer/JSF_Walkthrough8.html
As far as passing the values from one page to another is concerned you can use backing beans. More about backing beans here:
http://www.netbeans.org/kb/articles/jAstrologer-intro.html
http://www.coderanch.com/t/214065/JSF/java/backing-beans-vs-managed-beans
Hope i have understood and answered correctly to your question
Way to share values between beans
FacesContext facesContext = FacesContext.getCurrentInstance();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp = elFactory.createValueExpression(elContext, expression, Object.class);
return valueExp.getValue(elContext);
In above code "expression" would be something like #{xyzBean.beanProperty}
Since JSF uses singleton instances, you should be able to access the values from other beans. If you find more details on this technique, I am sure you'll get what you are looking for.
Add commandButton action attribute referencing to B'insert method
<h:commandLink action="#{b.insert}" value="insert"/>
In B'insert method,add d9 parameter as request parameter. Then return an arbitrary string from insert method.
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().getRequestMap().put("d9", d9);
Then go to faces context and add navigation from B to A with "from-outcome" as the arbitrary String you returned from insert method. But don't add redirect tag to navigation tags as it will destroy the request coming from B and the parameter you added (d9) will be cleared.
<from-outcome>return string of insert method</from-outcome>
<to-view-id>address of A</to-view-id>
Then you might get the "d9" in A class by fetching it from request map at its constructor or in a place where its more appropriate (getters). You might add it into a session scope or place it to a hidden variable if you want to keep track of it later.
in class A, when page is navigated, A should be initialized as it will be referenced.
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().getRequestMap().get("d9", d9);
Sorry i cant give full code, as i have no ide at here, its internet machine at work. I could not give details therefore.
In my opinion, the simplest way is 3-rd option - have both query and insert methods in same class. And you can do something like that:
public String query () {
//...
}
public String Insert() {
//insert
return Query(); }
If your classes are managed Beans you can load class A from class B and call A.query() in your insert method at the end. Also class A can have
<managed-bean-scope>session</managed-bean-scope>
parameter in faces-config.xml and it wouldn't be instantiated again when loaded.