JSF - Get SessionScoped Bean Instance

I have this setting in my web application. 2 beans:

1 ° Bean - checks login

@ManagedBean(name="login") @SessionScoped public class Login { private String nickname; private String password; private boolean isLogged; public String getNickname() { return nickname; } public void setNickname(String newValue) { nickname=newValue; } public String getPassword() { return password; } public void setPassword(String newValue) { password=newValue; } public void checkLogin() { ... i check on db the nickname and the password ... if(USER EXIST) { isLogged=true; } else { isLogged=false; } return true; } } 

2 ° Bean - User parameter management:

 @ManagedBean(name="user") @SessionScoped public class User { private String name; private String surname; private String mail; public User() { String[] record=null; Database mydb=Configuration.getDatabase(); mydb.connetti(); ArrayList<String[]> db_result=null; db_result=mydb.selectQuery("SELECT name, surname, mail, domicilio FROM users WHERE nickname='???????'"); int i = 0; while (i<db_result.size() ) { record=(String[]) db_result.get(i); i++; } } ... getter and setter methods... } 

As you can see, I would like to know how to get the alias set earlier on my login bean, so I can execute the query in my DB.

Actually I need to get an instance of the current Bean session: how can I get it? I should use things like session.getBean("login") :)

Hope this question is clear :)

+7
javabeans facelets jsf jsf-2
source share
2 answers

Use @ManagedProperty to enter it and use @PostConstruct to access it after the bean build (because in the regular constructor it will be null ).

 @ManagedBean @SessionScoped public class User { @ManagedProperty(value="#{login}") private Login login; @PostConstruct public void init() { // Put original constructor code here. } // Add/generate getters/setters and other boilerplate. } 

However, this is not the right approach. You would like to do it the other way around. Paste User into Login on @ManagedProperty(value="#{user}") and complete the task while the submit method is in effect.

You would also like to put the password in the WHERE . There is absolutely no need to drag the entire user table into the Java memory and define it one by one. Just let the database do the job and check if it returns zero or one row.

+10
source share

Also try using the following code:

  ExternalContext tmpEC; Map sMap; tmpEC = FacesContext.getCurrentInstance().getExternalContext(); sMap = tmpEC.getSessionMap(); login loginBean = (login) sMap.get("login"); 
+8
source share

All Articles