如何从Servlet访问托管bean和会话bean [英] How to access managed bean and session bean from Servlet

查看:78
本文介绍了如何从Servlet访问托管bean和会话bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的 commandLink 工作方式

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

然后在 myBean.java

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

假设用户名是 Peter 。然后,如果我点击 Peter ,我会将 selectedUser 设置为Peter的用户对象,然后重定向到个人资料页面,现在从 selectedUser 呈现信息。我想仅使用< h:outputText> 创建相同的效果,因此我想到了GET请求。所以我这样做

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)}" />

然后文本(String name,Long id)方法只返回

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

剩下的就是创建一个servlet,捕获 id ,查询数据库以获取用户对象,设置为 selectedUser ,重定向。
所以这是我的servlet

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"));
    }
}

现在我有 id ,如何访问我的会话bean以查询数据库中的用户,然后访问托管bean以设置用户 selectedUser ,然后重定向到 profile.jsf

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?

推荐答案

JSF使用托管bean名称作为密钥将会话范围的托管bean存储为会话属性。所以以下内容应该有效(假设JSF在会话之前已经创建了bean):

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">

以及与 profile.jsf相关联的请求范围bean中的以下内容

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

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

@PostConstruct
public void init() {
    sessionBean.setUser(em.find(User.class, userId));
    // ...
}

这篇关于如何从Servlet访问托管bean和会话bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆