In this tutorial we will see how to use a bean class in JSP with the help of jsp:useBean, jsp:setProperty and jsp:getProperty action tags.
Syntax of jsp:useBean:
<jsp: useBean id="unique_name_to_identify_bean" class="package_name.class_name" />
Syntax of jsp:setProperty:
<jsp:setProperty name="unique_name_to_identify_bean" property="property_name" />
Syntax of jsp:getProperty:
<jsp:getProperty name="unique_name_to_identify_bean" property="property_name" />
A complete example of useBean, setProperty and getProperty
1) We have a bean class Details where we are having three variables username, age and password. In order to use the bean class and it’s properties in JSP we have initialized the class like this in the userdetails.jsp page –
<jsp:useBean id="userinfo" class="beginnersbook.com.Details"></jsp:useBean>
We have used useBean action to initialize the class. Our class is in beginnersbook.com package so we have given a fully qualified name beginnersbook.com.Details.
2) We have mapped the properties of bean class and JSP using setProperty action tag. We have given ‘*’ in the property field to map the values based on their names because we have used the same property name in bean class and index.jsp JSP page. In the name field we have given the unique identifier which we have defined in useBean tag.
<jsp:setProperty property="*" name="userinfo"/>
3) To get the property values we have used getProperty action tag.
<jsp:getProperty property="propertyname" name="userinfo"/>
Details.java
package beginnersbook.com; public class Details { public Details() { } private String username; private int age; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
index.jsp
<html> <head><title> useBean, getProperty and setProperty example </title></head> <form action="userdetails.jsp" method="post"> User Name: <input type="text" name="username"><br> User Password: <input type="password" name="password"><br> User Age: <input type="text" name="age"><br> <input type="submit" value="register"> </form> </html>
userdetails.jsp
<jsp:useBean id="userinfo" class="beginnersbook.com.Details"></jsp:useBean> <jsp:setProperty property="*" name="userinfo"/> You have enterted below details:<br> <jsp:getProperty property="username" name="userinfo"/><br> <jsp:getProperty property="password" name="userinfo"/><br> <jsp:getProperty property="age" name="userinfo" /><br>
Output:
Leave a Reply