|
Accessing bean components from JSP |
|
|
Example below shows a JSP-page that inserts values into a bean object and then displays the values again.
One of the striking things about this JSP is that it does a fairly good bit of work but doesn't
contain any explicit Java code.
When you add a bean to a JSP, you can either create a new bean or use an existing one.
The JSP engine determines whether it needs to create a new bean for you based on the bean's id.
While adding a bean to a page, you must at least give the bean an id (which is just a name) and the bean's class.
The JSP engine first searches for an existing bean with the same id. If it doesn't find an existing bean,
the JSP engine creates a new instance of the class you specified.
////////////// here is a source code of our bean:
package beans;
////////////// Our bean is serializable. This will allow the server to save
////////////// it as a part of JSP context during restart or
////////////// recover operations
public class Person implements java.io.Serializable {
protected String firstName;
protected String lastName;
protected int age;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String aFirstName) {
firstName = aFirstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String aLastName) {
lastName = aLastName;
}
public int getAge() {
return age;
}
public void setAge(int anAge) {
age = anAge;
}
}
////////////// here is a page accessing a bean:
<%@page contentType="text/html"%>
<%-- Create an instance of the bean --%>
<jsp:useBean id="man" class="beans.Person"/>
<html>
<body>
<%-- Copy the parameters into the bean --%>
<jsp:setProperty name="man" property="*"/>
The bean values are:<br>
First Name: <jsp:getProperty name="man" property="firstName"/><br />
Last Name: <jsp:getProperty name="man" property="lastName"/><br />
Age: <jsp:getProperty name="man" property="age"/><br />
</body>
</html>
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.