Use useBean, setProperty, and getProperty commands in JSP, and usebeangetproperty
The useBean command is used to initialize a Java instance on the JSP page. The setProperty command is used to set the attribute value of the JavaBean instance. The getProperty command is used to output the attributes of the JavaBean instance.
Example:
The JavaBean code is as follows:
Package zhou;
Public class Person {
Private String name;
Private int age;
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
Public int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
Public Person (){}
Public Person (String name, int age ){
This. name = name;
This. age = age;
}
}
The JSP page code is as follows:
<% @ Page language = "java" contentType = "text/html; charset = ISO-8859-1"
PageEncoding = "ISO-8859-1" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = ISO-8859-1">
<Title> Insert title here </title>
</Head>
<Body>
<Jsp: useBean id = "p1" class ="Zhou. Person"Scope =" page "> </jsp: useBean>
<Jsp: setProperty name = "p1" property = "name" value = "zhou"/>
<Jsp: setProperty name = "p1" property = "age" value = "18"/>
<Jsp: getProperty name = "p1" property = "name"/>
<Jsp: getProperty name = "p1" property = "age"/>
</Body>
</Html>
Because a new class is provided for the web application, you need to restart tomcat. The page running result is as follows:
Zhou 18
However, the following problems are also found during the exercise:
(1) If the Person class is not placed in the name package, but the default package, it is found that the JavaBean cannot be accessed in JSP;
(2) If you use the import command in the header of the page to import the package where the JavaBean is located,
<% @ Page language = "java"Import = "zhou .*"ContentType = "text/html; charsets = ISO-8859-1"
PageEncoding = "ISO-8859-1" %>
When useBean command is used, the package where the JavaBean is located is not specified, that is
<Jsp: useBean id = "p1" class ="Person"Scope =" page "> </jsp: useBean>
We found that tomcat was started in Eclipse and the test passed. However, if you deploy it in tomcat, you cannot access the JavaBean.