开发者

JSF - Get the SessionScoped Bean instance

I have this configuration on my web application. 2 beans :

1° Bean - It checks the 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 ch开发者_StackOverflow社区eck on db the nickname and the password ...

        if(USER EXIST) {
            isLogged=true;
        } else {
            isLogged=false;
        }

        return true;
    }
}

2° Bean - Manage User parameter :

@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 get the nickname setted previously on my login bean, so i can do the query on my DB.

In fact i need to get the instance of the current-session bean login : how can I get it? I should use somethings like session.getBean("login") :)

Hope this question is clear :)


Use @ManagedProperty to inject it and use @PostConstruct to access it after bean's construction (because in a normal constructor it would be still 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.
}

That said, this is not the correct approach. You'd like to do it the other way round. Inject User in Login by @ManagedProperty(value="#{user}") and do the job during submit action method.

You'd also like to put the password in WHERE clause as well. There's absolutely no need to haul the entire users table into Java's memory and determine it one by one. Just let the DB do the job and check if it returns zero or one row.


Also try using the following code:

    ExternalContext tmpEC;
    Map sMap;
    tmpEC = FacesContext.getCurrentInstance().getExternalContext();
    sMap = tmpEC.getSessionMap();
    login loginBean = (login) sMap.get("login");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜