Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jsf 2 - how to get beans from view scope

I want to ask if i place my managed bean in session scope, then it is stored in session' Like if i have a bean like this

@ManagedBean
@SessionScoped
public class SessionScopedBean implements Serializable {

    .......

} //end of class SessionScopedBean

Then it stored in the session, and during my session i can get it using

session.getAttribut("SessionScopedBean");

This will give me the SessionScopedBean Object, and when session will get destroy, i will get null. Now i want to ask if i have my bean in view Scope, then how can i get it. Like

@ManagedBean
@ViewScoped
public class ViewScopedBean implements Serializable {

    .......

} //end of class ViewScopedBean

Now if the view is persist then this bean is in the view state, and when view changes, this bean will get destroy.Now i want to ask how can i get this bean from view state, if the view persist. Like

view.getAttrubute("ViewScopedBean");  //just a code. No actual implementation.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They're stored in the view map as available by UIViewRoot#getViewMap():

Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
ViewScopedBean viewScopedBean = (ViewScopedBean) viewMap.get("viewScopedBean");
// ...

Equivalently, you should be using the session map abstraction as well which is available by ExternalContext#getSessionMap() (you ultimately want to have zero javax.servlet import declarations throughout your JSF code):

Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
SessionScopedBean sessionScopedBean = (SessionScopedBean) sessionMap.get("sessionScopedBean");
// ...

See also:


Unrelated to the concrete problem, this may not be the best way. Look at @ManagedProperty if possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...