如何在JSP中获取Bean数据 [英] How to get Bean data in JSP

查看:276
本文介绍了如何在JSP中获取Bean数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在会话范围内将bean定义为PersonBean.

I have bean defined as PersonBean in session scope.

我想要的是在jsp页面中找到PersonBean.personId.

What I want is find the PersonBean.personId in jsp page.

我想在jsp页面中使用它,因为我想基于此personId进行一些计算.任何人都知道如何获得相同的东西.

I want it in jsp page, because I want to do some calculation based on this personId. Anyone have idea how to get the same.

在JSP中,我可以使用jsf进行打印

In JSP, I am able to print the same using jsf

<h:outputText value="#{PersonBean.personId}" />

但是我需要将此值分配给jsp中的某个整数值,如下所示.

However I need this value assigned to some integer value in jsp as shown below.

<h:outputText value="#{PersonBean.personId}" />
<%
   int i = new PersonBean().getPersonId;
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
%>

我认为int i = new PersonBean().getPersonId;可以工作,但是不工作.知道我如何得到这个吗?

I thought int i = new PersonBean().getPersonId; would work, however it is not working. Any idea how I get get this?

我也尝试过

<jsp:useBean id="sessionPersonalDataBean" class="com.sac.databean.PersonalInformationDataBean" scope="session"/>
<%
   out.print("my id is " + sessionPersonalDataBean.getPersonId());
%>

还是我得到的输出是my id is 0而不是my id is 0.

Still I get output as my id is 0 instead of my id is 0.

注意:

使用时,<h:outputText value=#{PersonalInformationDataBean.personId} />我得到正确的输出.

When I use, <h:outputText value=#{PersonalInformationDataBean.personId} /> I get proper output.

推荐答案

您应该避免在JSP中使用脚本,但是要回答您的问题:JSP是servlet.如果将一个bean存储在会话范围内的"PersonBean"属性下,则只需从会话中获取它即可:

You should avoid scriptlets in JSPs, but to answer your question: a JSP is a servlet. If a bean is stored in session scope under the attribute "PersonBean", then just get it from the session:

PersonBean p = (PersonBean) request.getSession().getAttribute("PersonBean");

如果将其存储在"PersonalInformationDataBean"属性下,则代码当然是

If it's stored under the attribute "PersonalInformationDataBean", the code is of course

PersonBean p = (PersonBean) request.getSession().getAttribute("PersonalInformationDataBean");

代码new PersonBean()创建一个新的PersonBean实例,因此,当然没有理由使该实例具有与会话中存储的实例相同的ID.这是相当基本的Java知识,我建议您在使用JSF之前先学习一些有关Java语言和基本OO概念的知识.

The code new PersonBean() creates a new PersonBean instance, so of course, there is no reason for this instance to have the same ID as the instance stored in the session. This is pretty basic Java stuff, and I would advise learning a bit more about the Java language and basic OO concepts before using JSF.

这篇关于如何在JSP中获取Bean数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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