How to use java beans in JSP using standard action element?

In order to use java beans in a jsp we have three standard action elements,
-Usebean
The usebean standard action either gives the existing bean instance reference or create one.It is of following form,
<jsp:useBean id=”refname” class=”package.classname” scope=”scopename”/>

id attribute: it uniquely identifies the particular bean instance. This attribute is mandatory because it will be used by the the two other action elements(getproperty and setProperty). In the generated servlet this id value is treated as a reference variable so this id can be used in expression and scriptlets also.

class attribute: It specifies the java class for the bean instance.

scope attribute:It specifies the scope in which the bean class resides. This attribute is optional. If we do not specify any scope then by default it takes page scope.

-setProperty:
it is used to provide data to the bean instance.
<jsp:useBean id=”refname” class=”package.classname” scope=”scopename”/>
<jsp:setProperty name=”refname” property=”name” value=”bhabani”/>

name attribute: To specify ehich bean to be used.(name same as useBean id)

property attribute: To specify which bean property is to be set

value attribute: To specify the value to the bean property.

-getProperty:
It is used to retrieve the values from the bean instance.
<jsp:getProperty name=”refname” property=”name”>

EXAMPLE:
Here the home page is an html page. when we fill the html form and request to the jsp then the jsp store the values in one bean class and again displays the values from the bean class.
Files required:
1)index.html
2)Myemp.jsp
3)Emp.java(bean class)

Index.html
<html>
<body>
< form action="Myemp.jsp">
name:<input type="text" name="empname"/><br>
id:<input type="text" name="empid"/><br>
city:<input type="text" name="city"/><br>
<input type=”submit” value=”click”/>
</form>
</body>
</html>

Emp.java:
package beans;

public class Emp {
private String empname;
private int empid;
private String city;

public String getCity() {
return city;
}

public int getEmpid() {
return empid;
}

public String getEmpname() {
return empname;
}

public void setCity(String city) {
this.city = city;
}

public void setEmpid(int empid) {
this.empid = empid;
}

public void setEmpname(String empname) {
this.empname = empname;
}}

Myemp.jsp:
<html>
<body>
<h1>YOU ENTERED VALUES AS BELOW</h1>
<jsp:useBean id="employee" class="beans.Emp"/>
<jsp:setProperty name="employee" property="*"/>
EMPLOYEE NAME:<jsp:getProperty name="employee" property="empname"/><br>
EMPLOYEE NO:<jsp:getProperty name="employee" property="empid"/><br>
CITY:<jsp:getProperty name="employee" property="city"/><br>
</body>
</html>
Do not put the Emp bean class in default package. Your program will not run.
Why the * is used? See the next question.

No comments:

Post a Comment