简体   繁体   English

Java / Java EE:从JSP调用getter方法

[英]Java/Java EE : to invoke getter method from JSP

I want to invoke a getter method (returns String value) of a Java class from JSP by using "jsp:usebean", but it returns a null value. 我想通过使用“ jsp:usebean”从JSP调用Java类的getter方法(返回String值),但是它返回空值。 What I don't understand is why it can't return the updated value. 我不明白的是为什么它不能返回更新后的值。

  1. Can someone shed some light on this? 有人可以阐明这一点吗?

  2. Should I use a Cookie to get the value from JSP? 我应该使用Cookie从JSP获取价值吗?

I'm not sure what you're using (Struts, plain Servlets, etc.) but essentially you need to add an attribute to the ServletRequest like: 我不确定您使用的是什么(Struts,普通的Servlet等),但实际上您需要向ServletRequest添加一个属性,例如:

class Person {
    private String firstName;
    // other fields, getters, setters
}

public void method(HttpServletRequest httpServletRequest) {
    Person p = new Person();
    p.setFirstName("Obama");
    httpServletRequest.setAttribute("person", p);
}

and in your JSP: 在您的JSP中:

<jsp:getProperty object="person" property="firstName" />

or if you use JSTL : 或者如果您使用JSTL

<c:out value="${person.firstName}"/>

It is simple. 很简单。

In java file: 在Java文件中:

package loga;
class bean{

String name;
public void setName(String Uname)
{
this.name=Uname;
}
public void getName()
{
return name;
}

In jsp file, call this method as: 在jsp文件中,将此方法称为:

<jsp:useBean id="object" class="loga.bean">
<jsp:setproperty name="object" property="Name" Value="XXXX"/>
<jsp:getProperty name="object" property="Name"/>
</jsp:usebean>

Here, the property indicates the method name of the getName() in the java class. 在此,该属性指示java类中getName()的方法名称。 To pass value from other controls use param property and give name of the control. 要从其他控件传递值,请使用param属性并提供控件的名称。

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

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