ViewScoped managed bean recreated on every request [duplicate] - jsf

I'm having an issue similar to this post and the answer from #BalusC with 3 solutions but:
I'm not using of the mentioned EL expressions
I don't want to go with the second solution (it's complex enough for me like this)
and partial state saving is set to false.
My code is as follows:
index.xhtml:
<?xml version="1.0" encoding="windows-1256" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form>
<p:panelMenu id="westMenu">
<p:submenu id="sub1" label="System Monitor">
<p:menuitem id="menu1" value="live monitoring"
action="#{menusBean.activateMenu('sub1_menu1')}"
update=":centerPane,westMenu"
disabled="#{menusBean.active['sub1_menu1']}" />
<p:menuitem id="menu2" value="reports"
action="#{menusBean.activateMenu('sub1_menu2')}"
update=":centerPane,westMenu"
disabled="#{menusBean.active['sub1_menu2']}" />
</p:submenu>
<p:submenu id="sub2" label="Charging System Nodes" />
<p:submenu id="sub3" label="Additional Nodes" />
</p:panelMenu>
</h:form>
<h:panelGroup id="centerPane">
...
</h:panelGroup>
</h:body>
</html>
MenusBean.java:
package menus;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.view.ViewScoped;
#ManagedBean
#ViewScoped
public class MenusBean implements Serializable{
private static final long serialVersionUID = -7793281454064343472L;
private String mainPage="sub1_menu1";
private Map<String, Boolean> active;
public MenusBean(){
System.out.println("MenusBean created");
active = new HashMap<>();
active.put(mainPage, true);
active.put("sub1_menu2", false);
}
public boolean activateMenu(String page){
active.put(mainPage, false);
active.put(page, true);
mainPage = page;
for (Map.Entry<String, Boolean> e : active.entrySet())
System.out.println(e.getKey()+":"+e.getValue());
return true;
}
public Map<String, Boolean> getActive() {
return active;
}
}
When executed, I get:
MenusBean created
MenusBean created
MenusBean created
How is this caused and how can I solve it?

This,
import javax.faces.view.ViewScoped;
is the JSF 2.2-introduced CDI-specific annotation, intented to be used in combination with CDI-specific bean management annotation #Named.
However, you're using the JSF-specific bean management annotation #ManagedBean.
import javax.faces.bean.ManagedBean;
You should then be using any of the scopes provided by the very same javax.faces.bean package instead. The right #ViewScoped is over there:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class MenusBean implements Serializable{
If you use the wrong combination, the bean behaves as a #RequestScoped bean and be recreated on each call.
Alternatively, if your environment supports CDI (GlassFish/JBoss/TomEE with Weld, OpenWebBeans, etc), then you could also replace #ManagedBean by #Named:
import javax.inject.Named;
import javax.faces.view.ViewScoped;
#Named
#ViewScoped
public class MenusBean implements Serializable{
It's recommended to move to CDI. The JSF-specific bean management annotations are candidate for deprecation in future JSF / Java EE versions as everything is slowly moving/unifying towards CDI.

Related

#PostConstruct of #ViewScoped is invoked on every request [duplicate]

This question already has an answer here:
#ViewScoped calls #PostConstruct on every postback request
(1 answer)
Closed 6 years ago.
I've got problem with opening dialog in JSF 2.2.7 and Primefaces 5. I've got button which opens a dialog and the problem is everytime when I click the button #PostConstruct method is executed. Why?
I want to invoke #PostConstruct only 1 time, but I don't want to change to scope to Session (with #SessionScope annotation it works perfectly).
It's my view:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:form id="f1">
<p:dialog widgetVar="trainingDialog2" id="d1">
<h:outputText value="#{userViewBean.errorMessage}" />
</p:dialog>
<br />
<p:dataTable id="dt1" value="#{userViewBean.infoList}" var="item">
<p:column>
<p:commandButton id="btn" update=":f1:d1"
oncomplete="PF('trainingDialog2').show()"
styleClass="ui-icon ui-icon-calendar">
<f:setPropertyActionListener value="#{item.id}"
target="#{userViewBean.errorMessage}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
It's my bean:
package pl.jrola.java.www.vigym.viewcontroller.beans.userview;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
#ManagedBean(name = "userViewBean")
#ViewScoped
public class UserViewBean implements Serializable {
private static final long serialVersionUID = 6994205182090669165L;
private String errorMessage;
private List<UserProfileInfoBean> infoList;
public List<UserProfileInfoBean> getInfoList() {
return infoList;
}
public void setInfoList(List<UserProfileInfoBean> infoList) {
this.infoList = infoList;
}
public UserViewBean() {
}
#PostConstruct
public void postConstruct() {
this.infoList = new ArrayList<UserProfileInfoBean>();
for (long i = 0; i < 3; i++) {
this.infoList.add(new UserProfileInfoBean(i));
}
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
You're mixing the annotations for JSF beans and CDI beans, effectively making the bean #RequestScoped, because it's the default for a #ManagedBean.
If you use JSF beans use:
javax.faces.bean.ManagedBean;
javax.faces.bean.ViewScoped;
If you wanna go for CDI beans use:
javax.inject.Named;
javax.faces.view.ViewScoped;
If your server supports CDI you should go for CDI beans.
Read more about the default scopes here:
What is the default Managed Bean Scope in a JSF 2 application?

CommandLink doesn't work. Tried everything

it's my first question on the site :) But first, sorry for my bad english, i'm learning :)
Plz, i need your help. I'm blocked with an application in JSF.
I have this
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<body>
<ui:composition template="./defaultTemplate.xhtml">
<ui:define name="content">
<h1 style="margin-bottom: 0px">#{msg.default_2}</h1>
<br/>
<ul style="padding-left: 0px">
<ui:repeat value="#{categoryMB.categories}" var="categorie">
<h:outputLabel value=" -==- " style="color: #FF8620; font-size: 10px; padding-left: 0px"></h:outputLabel>
<h:form>
<h:commandLink value="#{categorie.categoryname}" action="#{categoryMB.getItemsByCat(categorie.categoryid.id)}"/>
</h:form>
</ui:repeat>
</ul>
<ui:repeat value="#{categoryMB.listItems}" var="item">
<div class="itemCategory">
<h:graphicImage class="item-image" url="#{item.urlimage}"/>
<h:outputLabel value="#{item.price} €" class="prix"></h:outputLabel>
<br/>
<h2><h:outputLabel value="#{item.name}"></h:outputLabel></h2>
<br/>
<h:form>
<h:commandLink value="#{msg.default_14}" action="#{itemMB.linkItem(item.id)}"
></h:commandLink>
</h:form>
</div>
</ui:repeat>
</ui:define>
</ui:composition>
</body> </html>
Everything is good, except the second commandLink !
I can't execute the action. I always return on the same page...
I tried everything i could and i read all subjects about that on the site but i can't find a solution. Please, i'm asking you, help me. I'm going to be crazy.
My bean for categoryMB :
package managedBean;
import entityBean.Item;
import entityBean.Translatecategory;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.view.ViewScoped;
import sessionBean.ItemFacadeLocal;
import sessionBean.TranslatecategoryFacadeLocal;
/**
*
* #author Aurélien
*/
#ManagedBean
#ViewScoped
public class CategoryMB {
#EJB
private ItemFacadeLocal itemFacade;
#EJB
private TranslatecategoryFacadeLocal translatecategoryFacade;
#ManagedProperty("#{internationalizationMB}")
private InternationalizationMB language;
private List<Item> listItems;
/**
* Creates a new instance of CategoryMB
*/
public CategoryMB() {
}
public List<Translatecategory> getCategories () {
return translatecategoryFacade.findByLanguage(language.getLocale().getLanguage());
}
public void getItemsByCat (int idCat) {
setListItems(itemFacade.findByCat(idCat));
}
public InternationalizationMB getLanguage() {
return language;
}
public void setLanguage(InternationalizationMB language) {
this.language = language;
}
public List<Item> getListItems() {
return listItems;
}
public void setListItems(List<Item> listItems) {
this.listItems = listItems;
}
}
And my bean for itemMB :
package managedBean;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
#ManagedBean
#SessionScoped
public class ItemMB implements Serializable {
private int idItem;
/**
* Creates a new instance of ItemMB
*/
public ItemMB() {
}
public int getIdItem() {
return idItem;
}
public void setIdItem(int idItem) {
this.idItem = idItem;
}
public String linkItem(int id)
{
setIdItem(id);
return "item";
}
}
You're mixing CDI #SessionScoped with JSF 2.x #SessionScoped. This is noted in your imports:
import javax.enterprise.context.SessionScoped;
#ManagedBean
#SessionScoped
public class ItemMB implements Serializable {
//...
}
This makes your managed bean to have the default scope, which in JSF 2 is #RequestScoped, so your managed bean will be re created on every request.
Fix your import to:
import javax.faces.bean.SessionScoped;
If you happen to use JSF 2.2.x, start working everything with CDI 1.1. Use #Named for your managed beans and use javax.faces.view.ViewScoped for #ViewScoped.
More info:
What's new in JSF 2.2. CDI compatible #ViewScoped

#ViewScoped bean recreated on every postback request when using JSF 2.2

I'm having an issue similar to this post and the answer from #BalusC with 3 solutions but:
I'm not using of the mentioned EL expressions
I don't want to go with the second solution (it's complex enough for me like this)
and partial state saving is set to false.
My code is as follows:
index.xhtml:
<?xml version="1.0" encoding="windows-1256" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form>
<p:panelMenu id="westMenu">
<p:submenu id="sub1" label="System Monitor">
<p:menuitem id="menu1" value="live monitoring"
action="#{menusBean.activateMenu('sub1_menu1')}"
update=":centerPane,westMenu"
disabled="#{menusBean.active['sub1_menu1']}" />
<p:menuitem id="menu2" value="reports"
action="#{menusBean.activateMenu('sub1_menu2')}"
update=":centerPane,westMenu"
disabled="#{menusBean.active['sub1_menu2']}" />
</p:submenu>
<p:submenu id="sub2" label="Charging System Nodes" />
<p:submenu id="sub3" label="Additional Nodes" />
</p:panelMenu>
</h:form>
<h:panelGroup id="centerPane">
...
</h:panelGroup>
</h:body>
</html>
MenusBean.java:
package menus;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.view.ViewScoped;
#ManagedBean
#ViewScoped
public class MenusBean implements Serializable{
private static final long serialVersionUID = -7793281454064343472L;
private String mainPage="sub1_menu1";
private Map<String, Boolean> active;
public MenusBean(){
System.out.println("MenusBean created");
active = new HashMap<>();
active.put(mainPage, true);
active.put("sub1_menu2", false);
}
public boolean activateMenu(String page){
active.put(mainPage, false);
active.put(page, true);
mainPage = page;
for (Map.Entry<String, Boolean> e : active.entrySet())
System.out.println(e.getKey()+":"+e.getValue());
return true;
}
public Map<String, Boolean> getActive() {
return active;
}
}
When executed, I get:
MenusBean created
MenusBean created
MenusBean created
How is this caused and how can I solve it?
This,
import javax.faces.view.ViewScoped;
is the JSF 2.2-introduced CDI-specific annotation, intented to be used in combination with CDI-specific bean management annotation #Named.
However, you're using the JSF-specific bean management annotation #ManagedBean.
import javax.faces.bean.ManagedBean;
You should then be using any of the scopes provided by the very same javax.faces.bean package instead. The right #ViewScoped is over there:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class MenusBean implements Serializable{
If you use the wrong combination, the bean behaves as a #RequestScoped bean and be recreated on each call.
Alternatively, if your environment supports CDI (GlassFish/JBoss/TomEE with Weld, OpenWebBeans, etc), then you could also replace #ManagedBean by #Named:
import javax.inject.Named;
import javax.faces.view.ViewScoped;
#Named
#ViewScoped
public class MenusBean implements Serializable{
It's recommended to move to CDI. The JSF-specific bean management annotations are candidate for deprecation in future JSF / Java EE versions as everything is slowly moving/unifying towards CDI.

ViewParam and session scoped bean

I defined viewParam to process a GET request but the session bean is null.
/treeTable2.xhtml #28,119 value="#{conformanceProfileController.dataValueAssertionController.library_line}": Target Unreachable, identifier 'conformanceProfileController' resolved to null
GET request:
treeTable2.jsf?category=Message
XHTML code
<f:metadata>
<f:viewParam name="category" value="#{conformanceProfileController.category}" />
</f:metadata>
The Bean
#ManagedBean
#SessionScoped
public class ConformanceProfileController implements Serializable {
private String category;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
My development server is Tomcat 7.0 and I use Mojarra 2.1.0
EDIT: I created a simplified version with a new page and new bean. The code in the post is the same as the one on my machine.
XHTML Code:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:head>
</h:head>
<f:metadata>
<f:viewParam name="category" value="#{myBean.category}" />
</f:metadata>
<h:body>
</h:body>
</html>
MyBean:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class MyBean implements Serializable {
private String category;
public MyBean() {
System.out.println("Creation");
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
The GET request: treeTable3.jsf?category=Message
The error message: /treeTable3.xhtml #8,60 value="#{myBean.category}": Target Unreachable, identifier 'myBean' resolved to null
Mojarra 2.1.0 do not work in Tomcat/Jetty due to a bug in annotation scanning. Upgrade to at least 2.1.1 or the current 2.1.3.
This has nothing to do with view parameters or session scoped beans. It will just fail in all cases where you expect a #ManagedBean.
Give the #Named annotation a try: http://download.oracle.com/javaee/6/tutorial/doc/gjbak.html

CDI SessionScoped Bean results in two instances in same session

I've got two instances of a SessionScoped CDI bean for the same session. I was under the impression that there would be one instance generated for me by CDI, but it generated two. Am I misunderstanding how CDI works, or did I find a bug?
Here is the bean code:
package org.mycompany.myproject.session;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
#Named #SessionScoped public class MyBean implements Serializable {
private String myField = null;
public MyBean() {
System.out.println("MyBean constructor called");
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)fc.getExternalContext().getSession(false);
String sessionId = session.getId();
System.out.println("Session ID: " + sessionId);
}
public String getMyField() {
return myField;
}
public void setMyField(String myField) {
this.myField = myField;
}
}
Here is the Facelet code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<f:view contentType="text/html" encoding="UTF-8">
<h:head>
<title>Test</title>
</h:head>
<h:body>
<h:form id="form">
<h:inputText value="#{myBean.myField}"/>
<h:commandButton value="Submit"/>
</h:form>
</h:body>
</f:view>
</html>
Here is the output from deployment and navigating to page:
INFO: Loading application org.mycompany_myproject_war_1.0-SNAPSHOT at /myproject
INFO: org.mycompany_myproject_war_1.0-SNAPSHOT was successfully deployed in 8,237 milliseconds.
INFO: MyBean constructor called
INFO: Session ID: 175355b0e10fe1d0778238bf4634
INFO: MyBean constructor called
INFO: Session ID: 175355b0e10fe1d0778238bf4634
Using GlassFish 3.0.1
Ryan, as covener already wrote, the constructor will also get called for each and every proxy for that bean. This is a standard behaviour of all proxy mechanisms which provide not only interface-proxying (like java.lang.reflect.proxy stuff) but real class-proxying.
Also imagine that the ct will also be called for each and every serialization. So if you work on a heavily load balanced cluster, you will see this lots of times. So please use #PostConstruct for beans in general.
LieGrue,
strub
It's likely that your CDI implementation calls the underlying beans default constructor when newing up proxies to use for injection points -- this is the default behavior of javassist which is used in weld and openwebbeans.
Avoid heavy lifting in your default constructor, moving it into #PostConstruct if you can!

Resources