如何在JSP中设置和获取bean的属性?

在此示例中,您将学习如何设置和获取在JSP页面中定义的Java对象属性的值。对于此示例,我们首先开始创建一个名为的变量,该变量customer将具有类的Customer类型。为了创建这个变量,我们使用<jsp:useBean> action。

创建customer变量后,我们可以customer使用<jsp:setProperty>操作设置bean的属性值。为了获得customerbean的属性值,我们使用<jsp:getProperty>动作。

and动作中的name属性引用了我们的bean。该属性告诉我们要设置或获取的属性。要设置属性的值,我们使用属性。setPropertygetPropertycustomerpropertyvalue

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSP - Bean Property Demo</title>
</head>
<body>

<jsp:useBean id="customer"/>
<jsp:setProperty name="customer" property="id" value="1"/>
<jsp:setProperty name="customer" property="firstName" value="John"/>
<jsp:setProperty name="customer" property="lastName" value="Doe"/>
<jsp:setProperty name="customer" property="address" value="Sunset Road"/>

Customer Information: <%= customer.toString() %><br/>
Customer Name: <jsp:getProperty name="customer" property="firstName"/>
<jsp:getProperty name="customer" property="lastName"/>

</body>
</html>

这是我们的Customerbean的代码。这个bean包含属性,如id,firstName,lastName和address。

package org.nhooo.example.bean;

public class Customer {
    private int id;
    private String firstName;
    private String lastName;
    private String address;

    public Customer() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", firstName='" + firstName + ''' +
                ", lastName='" + lastName + ''' +
                ", address='" + address + ''' +
                '}';
    }
}

我们访问JSP页面,我们将看到以下输出:

Customer Information: Customer{id=1, firstName='John', lastName='Doe', address='Sunset Road'}Customer Name: John Doe