How to get Bean data in JSP

南楼画角 提交于 2019-12-04 06:34:32

问题


I have bean defined as PersonBean in session scope.

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

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.

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

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

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;
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
%>

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

Update 1

I also tried

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

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

NOTE:

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


回答1:


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

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

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

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.



来源:https://stackoverflow.com/questions/11373665/how-to-get-bean-data-in-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!