Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access managed bean and session bean from Servlet [duplicate]

Here is how my commandLink work

 <p:dataTable value="#{myBean.users}" var="item">
     <p:column>
         <h:commandLink value="#{item.name}" action="#{myBean.setSelectedUser(item)}" />     
     </p:column>
 </p:dataTable>

then in myBean.java

 public String setSelectedUser(User user){
     this.selectedUser = user;
     return "Profile";
 }

Let assume the user name is Peter. Then if I click on Peter, I will set the selectedUser to be Peter's User Object, then redirect to the profile page, which now render information from selectedUser. I want to create that same effect only using <h:outputText>, so GET request come to mind. So I do this

 <h:outputText value="{myBean.text(item.name,item.id)}" />

then the text(String name, Long id) method just return

"<a href=\"someURL?userId=\"" + id + ">" + name + "</a>"

all that left is creating a servlet, catch that id, query the database to get the user object, set to selectedUser, the redirect. So here is my servlet

public class myServlet extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Long userId = Long.parseLong(request.getParameter("userId"));
    }
}

Now I have the id, how do I access my session bean to query the database for the user, then access managed bean to set the user to selectedUser, then redirect to profile.jsf?

like image 631
Thang Pham Avatar asked Oct 13 '10 00:10

Thang Pham


1 Answers

JSF stores session scoped managed beans as session attribute using managed bean name as key. So the following should work (assuming that JSF has already created the bean before in the session):

MyBean myBean = (MyBean) request.getSession().getAttribute("myBean");

That said, I have the feeling that you're looking in the wrong direction for the solution. You could also just do like follows:

<a href="profile.jsf?userId=123">

with the following in a request scoped bean associated with profile.jsf

@ManagedProperty(value="#{param.userId}")
private Long userId;

@ManagedProperty(value="#{sessionBean}")
private SessionBean sessionBean;

@PostConstruct
public void init() {
    sessionBean.setUser(em.find(User.class, userId));
    // ...
}
like image 133
BalusC Avatar answered Sep 22 '22 04:09

BalusC