Setting and getting JavaBean properties in JSP
This example shows how to set and get properties of java bean class in jsp page. The important rules of setting and getting of properties are following:
- The set method name and property name must be same but with first letter in upper case and prefix with 'set'.
- The return type of the set method should be void and should take only one input parameter.
- The get method name and property name must be same but with first letter in upper case and prefix with 'get'.
- The return type of the get method can be String or any primitive type and should take no input parameter.
Source code of the JSPBean.java
package roseindia;
|
useBean.jsp
<?xml version="1.0"?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2"> <html> <body> <jsp:useBean id="b" class="roseindia.JSPBean"/> <jsp:setProperty name="b" property="developer" /> Developer = <jsp:getProperty name="b" property="developer"/><br/> <jsp:setProperty name="b" property="company" /> Company = <jsp:getProperty name="b" property="company"/><br/> <jsp:setProperty name="b" property="city" /> City = <jsp:getProperty name="b" property="city"/><br/> </body> </html> </jsp:root> |
Compile this program on the command prompt:
C:\apache-tomcat-6.0.16\webapps\ServletExample\WEB-INF\classes>javac -d . JSPBean.java |
Start the tomcat and run the jsp file on browser as given url: http://localhost:8080/ServletExample/jsp/useBean.jsp then the output will be displayed as below: