What is meant by Java Bean? How it can be used in JSP scripts? Also Explain jsp:useBean, jsp:setProperty and jsp:getProperty Explain with suitable example.

 JAVA BEANS IN JSP

JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions is a JavaBeans component. Following are the unique characteristics that distinguish a JavaBean from other Java classes:

- It must provide a default, no-argument constructor.

- It should be serializable and implement the Serializable interface. It may have a number of properties which can be read or written.

- It may have a number of "getter" and "setter" methods for the properties.

JavaServer Pages technology directly supports using JavaBeans components with standard JSP language elements. We can easily create and initialize beans and get and set the values of their properties.

a) jsp:useBean

The use Bean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP. The full syntax for the useBean tag is as follows:

<jsp: useBean id="beans name" class="class name" scope="beans scope" />

Here values for the scope attribute could be page, request, session or application based on our requirement. The value of the id attribute may be any value as a long as it is a unique name among other useBean declarations in the same JSP.

Example

<html>

<head>

<title>useBean Example</title>

</head>

<body>

<jsp:useBean id="date" class="java.util.Date" />

<p>The date/time is <%= date %>

</body>

</html>

Output

This would produce following result: The date/time is Thu Sep 30 11:18:11 GST 2010

b) jsp:setProperty and jsp:getProperty

Along with <jsp:useBean...>, we can use <jsp:getProperty/> action to access get methods and <jsp:setProperty/> action to access set methods. Here is the full syntax:

<jsp:useBean id="beans id" class="class name" scope="beans scope">

<jsp: setProperty name="beans id" property="property name" <jsp:getProperty name="beans id" property="property name"/>

value="value"/>

</jsp:useBean>

The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action. The property attribute is the name of the get or set methods that should be invoked.


Comments

Popular posts from this blog

What are different steps used in JDBC? Write down a small program showing all steps.

Discuss classification or taxonomy of virtualization at different levels.

Pure Versus Partial EC