JSF rendered form not working - jsf

I have this problem with JSF rendering. I have this bean containing boolean type value ulogovan.
#Named("sessionBean")
#SessionScoped
public class SessionBean implements Serializable{
private boolean ulogovan;
private Zaposleni ulogovanZaposleni;
public SessionBean() {
ulogovan = false;
ulogovanZaposleni = null;
}
public boolean getUlogovan() {
return ulogovan;
}
public void setUlogovan(boolean ulogovan) {
this.ulogovan = ulogovan;
}
I have to show a form depending on a value of ulogovan. Here is the begining of the form:
<h:form id="form" rendered="#{sessionBean.ulogovan == true}">

Because ulogovan = false; so when you said #{sessionBean.ulogovan == true} that mean false == true which is false. Thus, your form will not be rendered unless you set ulogovan to be true.
If you want your form to be rendered depending on the value of ulogovan, just do it like this:
<h:form id="form" rendered="#{sessionBean.ulogovan}">

You can include #PostConstruct annotation on init() method.
So before rendering the page this method will be called first.
You can set the condition in this you wish
#Named("sessionBean")
#SessionScoped
public class SessionBean implements Serializable{
private boolean ulogovan;
private Zaposleni ulogovanZaposleni;
#PostConstruct
public void init() {
setUlogovan(false);
ulogovanZaposleni = null;
}
public boolean getUlogovan() {
return ulogovan;
}
public void setUlogovan(boolean ulogovan) {
this.ulogovan = ulogovan;
}
This will work definately.

Related

Set value to ManagedProperty

I'm trying to set a value to my ManagedProperty but I'm getting the null result when I try to print this.
I'd like to set the Bean Class to use it in my query.
I've been tryin' set String, Class, but all the times it returned a null value.
Can anyone help me?
#ManagedBean
public class FilialBean extends BaseBean implements Serializable{
private Filial filial;
private List<Filial> filiais;
#ManagedProperty("#{entidadeService}")
private EntidadeService service;
#PostConstruct
public void init(){
service.setFaces(Filial.class);
filial = new Filial();
filiais = (List<Filial>) (List) service.getbasesEntidades();
}
//GETTERS AND SETTERS
}
#ManagedBean(name="entidadeService", eager=true)
#ApplicationScoped
public class EntidadeService implements Serializable{
private List<EntidadeBase> basesEntidades;
private Class faces;
#PostConstruct
public void init(){
System.out.println(faces.getSimpleName());
try{
EntityManager manager = JPAUtil.getEntityManager();
Query query = manager.createQuery("SELECT e FROM Filial e WHERE e.ativo = :ativo");
query.setParameter("ativo", true);
this.basesEntidades = query.getResultList();
}
catch(Exception e){
e.printStackTrace();
}
}
public List<EntidadeBase> getbasesEntidades() {
return basesEntidades;
}
public Class getFaces() {
return faces;
}
public void setFaces(Class faces) {
this.faces = faces;
}
}
Have you check that #ManagedBean has same package in both classes?
I ran into same problem, a property with null value executing Post Construct method and this is the problem, one class had javax.annotation.ManagedBean (CDI) annotation and the other had javax.faces.bean.ManagedBean (JSF) annotation.
In my case I needed both classes with JSF annotations...

Show how many Users logged in with JSF

i trie to run this code
#ManagedBean
#ApplicationScoped
public class Controller implements Serializable {
private static final long serialVersionUID = 1L;
private Benutzer benutzer;
private List<Erfasst> bisherErfasst = new ArrayList<Erfasst>();
private EntityManagerFactory emf = Persistence
.createEntityManagerFactory("CP Kontrolle");
private static Controller instance = new Controller();
public Benutzer getBenutzer() {
return benutzer;
}
public boolean anmelden(String email, int kdnr) {
EntityManager em = emf.createEntityManager();
Query query = em
.createQuery("SELECT b FROM Benutzer b WHERE b.email = :email AND b.kdnr = :kdnr");
query.setParameter("email", email);
query.setParameter("kdnr", kdnr);
List<Benutzer> liste = query.getResultList();
em.close();
if (liste.size() == 1) {
benutzer = liste.get(0);
AngemeldeteBenutzer.getAb().hinzufuegen(benutzer);
return true;
} else {
return false;
}
}
public static Controller getInstance() {
return instance;
}
[....]
}
}
The above code is my ControllerBean. From the Login-Form, user data will be checked in the "anmelden" Class and return true or false if it was successfully.If successfully, the user will be store into a list, as you can see.
#ManagedBean
#ApplicationScoped
public class AngemeldeteBenutzer implements Serializable {
private static final long serialVersionUID = 1L;
private List<Benutzer> online = new LinkedList<Benutzer>();
private static AngemeldeteBenutzer ab = new AngemeldeteBenutzer();
public static AngemeldeteBenutzer getAb() {
return ab;
}
public List<Benutzer> getOnline() {
return online;
}
public void hinzufuegen(Benutzer benutzer) {
online.add(benutzer);
}
}
This is my other Bean, which store the successfully logged user into a list.
Now i want to list all user into my table, but my table is still empty. No errors!
<h:panelGrid columns="2" id="onlinePanel" >
<h:dataTable value="#{angemeldeteBenutzer.online}" var="on">
<h:column>
<f:facet name="header">Email</f:facet>
<h:outputText value="#{on.email}"></h:outputText>
</h:column>
</h:dataTable>
</h:panelGrid>
The mistake is here:
private static Controller instance = new Controller();
public static Controller getInstance() {
return instance;
}
private static AngemeldeteBenutzer ab = new AngemeldeteBenutzer();
public static AngemeldeteBenutzer getAb() {
return ab;
}
You seem to have missed the point of a bean management framework with dependency injection support. You seem to be expecting that #{angemeldeteBenutzer} in the JSF page is referring exactly the same instance as you manually created there with new operator and are filling with users.
This is Wrong! You have there two instances of the class, one automatically created by JSF and available via #{angemeldeteBenutzer} and another one manually created by yourself and available via that getAb() method only.
Get rid of all those static fields and methods. They don't belong there. Instead, use #ManagedProperty to let JSF inject managed beans in each other. Add this code to the Controller class.
#ManagedProperty("#{angemeldeteBenutzer}")
private AngemeldeteBenutzer ab;
public AngemeldeteBenutzer getAb() {
return ab;
}
public void setAb(AngemeldeteBenutzer ab) {
this.ab = ab;
}
And replace in the same Controller class this line
AngemeldeteBenutzer.getAb().hinzufuegen(benutzer);
by
ab.hinzufuegen(benutzer);
Note: if you're already on Java EE 7, consider using CDI #Named instead of JSF #ManagedBean. When injecting via #Inject instead of #ManagedProperty, you don't need those ugly getter/setter anymore.
#Named
#ApplicationScoped
public class AngemeldeteBenutzer {
}
#Named
#ApplicationScoped
public class Controller {
#Inject
private AngemeldeteBenutzer ab;
}
Unrelated to the concrete problem, the Controller doesn't seem to be a legit application scoped bean. It looks too much like a view scoped bean due that view-specific variables and business logic. Make sure you understand the scopes: How to choose the right bean scope?

Why cant I get the value of a SessionScoped bean in the constructor of another bean?

I have this SessionScoped bean:
#ManagedBean
#SessionScoped
public class LoginBean implements Serializable {
/**
* Creates a new instance of LoginBean
*/
public LoginBean() {
this.usuario = new Usuario();
}
private Usuario usuario;
//getter & setter
}
The Usuario class:
public class Usuario {
public Usuario() {
}
private String password;
private String nombre;
private int idPlanta;
private int nivel;
private String idUsuario;
//getters & setters
}
And I want to get the value of the property idPlanta from the SessionScoped bean (LoginBean) here (in the constructor) see the comments:
#ManagedBean
#ViewScoped
public class PrincipalBean implements Serializable {
public PrincipalBean() {
System.out.println(this.login.getUsuario().getIdPlanta());
//AT THIS POINT THE VALUE OF idPlanta IS 0 but in the session I have 1...
//Method that uses the idPlanta value as a parameter
}
#ManagedProperty(value = "#{loginBean}")
private LoginBean login;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
}
But when I show the value in the view it shows the value that really is in the Session idPlanta = 1. I dont understand why I cant get the value of that property in the constructor of that ViewScoped bean (PrincipalBean). I show the value in the view here(I know I can get it directly fron the LoginBean but this is just to show that the property login in PrincipalBean has the Session value):
<h:outputText class="titulo" value="Bienvenido(a) #{principalBean.login.usuario.nombre} Planta #{principalBean.login.usuario.idPlanta}" />
The value of idPlanta in PrincipalBean is very important because I use it as a method parameter to show more info when the view is showed.
Please help me. I still learning JSF.
You need to be using these values after the bean has been constructed. When your constructor is called, your bean has net yet been initialzed - therefore the injections have not yet happend. Using the #PostConstruct method you will be able to access the desired values from the injected objects.
For example :
#ManagedBean
#ViewScoped
public class PrincipalBean implements Serializable {
public PrincipalBean() {
}
#PostConstruct
public init() {
System.out.println(this.login.getUsuario().getIdPlanta());
//AT THIS POINT THE VALUE OF idPlanta IS 0 but in the session I have 1...
//Method that uses the idPlanta value as a parameter
}
#ManagedProperty(value = "#{loginBean}")
private LoginBean login;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
}
See Also
Why use #PostConstruct?
Injecting Managed Beans In JSF 2.0
JSF injection with managed property, good pattern?

Managed property between SessionScoped ManagedBeans

I have the following problem!
On one of my sites i have a button:
<h:commandButton value="IDA Analyzer Results" action="#{SelectionBean.monitoringLog()}"/>
The method it calls with some part of the bean:
#ManagedBean(name = "SelectionBean")
#SessionScoped
public class TableSelectionBean {
private List<String> analyzerLog = new ArrayList<String>();
public String monitoringLog() throws FileNotFoundException, IOException{
String fileName = "/opt/IDA2/Linux/bin/"+"filtered_"+selectionMonitoringData.get(0).getMonitoringName()+"_result.txt";
if(selectionMonitoringData.get(0).getIsExecuted())
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
String line;
while ((line=br.readLine()) != null) {
getAnalyzerLog().add(line);
}
} finally {
br.close();
System.out.println(getAnalyzerLog());
}
}
return "analyzerresult.xhtml";
}
After i click this button as you can see it navigates me to an other page:
<h:body>
<h:form>
<h:commandButton value="hi" action="#{AnalyzerBean.myMethod()}"></h:commandButton>
</h:form>
</h:body>
Here is the Bean:
#ManagedBean(name = "AnalyzerBean")
#SessionScoped
public class AnalyzerResultBean {
#ManagedProperty(value="#{SelectionBean.analyzerLog}")
private List<String> analyzerLog;
public void myMethod(){
System.out.print(analyzerLog);
}
/**
* #return the analyzerLog
*/
public List<String> getAnalyzerLog() {
return analyzerLog;
}
/**
* #param analyzerLog the analyzerLog to set
*/
public void setAnalyzerLog(List<String> analyzerLog) {
this.analyzerLog = analyzerLog;
}
So when I'm trying to use this Managed property it says:
The scope of the object referenced by expression #{SelectionBean.analyzerLog}, view, is shorter than the referring managed beans (AnalyzerBean) scope of session but as you can see both of the is Session Scoped. What could be the problem?
If you use JSF 2.x and you want to navigate analyzerresult.xhtml page return analyzerresult
public String monitoringLog() throws FileNotFoundException, IOException{
return "analyzerresult";
}
.xhtml extension is not needed.

JSF - Set multiple values on #ManagedProperty in a single bean

I need to set 2 different ManagedProperty on the same bean. So i tried :
#ManagedBean(name="selector")
#RequestScoped
public class Selector {
#ManagedProperty(value="#{param.page}")
#ManagedProperty(value="#{param.profile_page}")
private String page;
private String profile_page;
public String getProfile_page() {
if(profile_page==null || profile_page.trim().isEmpty()) {
this.profile_page="main";
}
return profile_page;
}
public void setProfile_page(String profile_page) { this.profile_page = profile_page; }
public String getPage() {
if(page==null || page.trim().isEmpty()) {
this.page="homepage";
}
return page;
}
public void setPage(String page) { this.page=page; }
}
but unfortunatly i can't write 2 different #ManagedProperty : it says duplicate annotations. How can I fix it?
Another : when i return this value, its a String, and i need to confrontate. This syntax :
<h:panelGroup rendered="#{selector.profile_page.compareTo("main")}">
<ui:include src="/profile/profile_main.xhtml" />
</h:panelGroup>
will work?
Cheers
The annotations have to be declared directly before the class, method or field of interest.
So:
#ManagedProperty(value="#{param.page}")
private String page;
#ManagedProperty(value="#{param.profile_page}")
private String profile_page;

Resources