The following example code demonstrates useBean Directive in JSP.
Person.java
public class Person {
private String name;
private int age;
private String address;
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
}
PersonPage.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Person Page</title>
</head>
<body>
<jsp:useBean id="person" class="Person" scope="page">
<jsp:setProperty name="person" property="name" value="John Doe"/>
<jsp:setProperty name="person" property="age" value="30"/>
<jsp:setProperty name="person" property="address" value="123 Main St"/>
</jsp:useBean>
<h2>Person Details</h2>
<p>Name: <%= person.getName() %></p>
<p>Age: <%= person.getAge() %></p>
<p>Address: <%= person.getAddress() %></p>
</body>
</html>
In this example, Person
is a Java class that has three properties: name
, age
, and address
. The PersonPage.jsp
uses the useBean
directive to create an instance of the Person
class and sets its properties using the setProperty
directive.
The properties of the Person
object are then displayed on the page using expressions. When the PersonPage.jsp
is executed, it will display the person’s name, age, and address on the page.