Java – how to access managed beans and session beans from servlets

See the English answer > get JSF managed bean by name in any servlet related Class6

<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 In Java

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

Suppose the user name is Peter Then, if I click Peter, I will set selecteduser as Peter's user object and redirect to the profile page, which now presents information from selecteduser I just want to use < H: outputtext & gt;, Create the same effect, so get requests are remembered So I did

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

Then the text (string name, long ID) method just returns

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

All that's left is to create a servlet, capture the ID, query the database to get the user object, set it to selecteduser, and redirect So this 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 that I have ID, how can I access my session bean to query the user's database, then access the managed bean to set the user as selecteduser, and then redirect to profile jsf?

Solution

JSF stores session scope managed beans as session properties and uses managed bean names as keywords So the following work (assuming that JSF has been created in the session):

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

In other words, I have a feeling that you are in the wrong direction of the solution You can also do this:

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

In connection with profile The request scope bean associated with JSF has the following contents

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

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

@postconstruct
public void init() {
    sessionBean.setUser(em.find(User.class,userId));
    // ...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>