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

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

问题描述

这是我的 commandLink 的工作方式

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>

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

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

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

剩下的就是创建一个 servlet,捕获 id,查询数据库以获取 user 对象,设置为 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 以查询 user 的数据库,然后访问托管 bean 以设置 userselectedUser,然后重定向到 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

@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天全站免登陆