简体   繁体   English

在 jsp 页面中调用一个 bean 方法

[英]invoking a bean method in jsp page

I have a class which would create a bean and the bean has few get and set methods(for example setId, and getId, now im including this java file in a jsp page, now my question is how to forward the values returned by the bean to the jsp file?我有一个 class,它会创建一个 bean,bean 几乎没有 get 和 set 方法(例如 setId 和 getId,现在我将这个 java 文件包含在 jsp 页面中,现在我的问题是如何转发 bean 返回的值到 jsp 文件?

Kindly help.请帮忙。

Just put the bean in the scope you need it to be available.只需将 bean 放入您需要的 scope 中即可。 For example, if it's the User class which needs to be in the session scope:例如,如果是User class 需要在 session scope 中:

request.getSession().setAttribute("user", user);

This way the user instance is available by the attribute name "user" in EL as follows ${user} .这样, user实例就可以通过 EL 中的属性名称"user"获得,如下所示${user} Then, to access its properties as done by the getter methods, just use the period .然后,要像 getter 方法那样访问它的属性,只需使用句点. operator in EL wherein you specify the property name. EL 中的运算符,您可以在其中指定属性名称。

${user.id} 
${user.firstname}
${user.lastname}
...

No need to put all attributes individually in request scope.无需将所有属性单独放入请求 scope 中。

See also:也可以看看:

This should be something you have in your servlet:这应该是你的 servlet 中的东西:

MyBean bean = new MyBean(); //This should be your bean
Object o1 = bean.getObject1(); //Please don't use Object, use the correct type
Object o2 = bean.getObject2();

request.setAttribute("name",o1); //name can be anything you want
request.setAttribute("test",o2);
//forward to JSP

======================================= =======================================

In your jsp you could use EL:在您的 jsp 中,您可以使用 EL:

<!-- This is the firstObject -->
<p>${name}</p>

<!-- This is the second Object -->
<b>${test}</b>

======================================= =======================================

Or the older style with use:Bean:或者使用旧样式:Bean:

<!-- This is the first Object, use the correct type in class -->
<jsp:useBean id="name" scope="request" class="java.lang.Object" />

Now you can access the properties of the bean:现在您可以访问 bean 的属性:

<jsp:getProperty name="name" property="firstName"/>

or:要么:

<%= name.getFirstName() %>

======================================= =======================================

Normally it is very rare that the second part is used.通常很少使用第二部分。 Most people use EL these days.现在大多数人都在使用 EL。 But i just included it, to cover everything但我只是把它包括在内,以涵盖一切

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM