Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Jsp Using Beans in JSP. A brief introduction to JSP and Java Beans.

Related Tutorials


 
 

Share on Google+Share on Google+

Using Beans in JSP. A brief introduction to JSP and Java Beans.

Advertisement
Using Beans in JSP. A brief introduction to JSP and Java Beans. USING BEANS IN JSP Java Beans Java Beans are reusable components. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a

USING BEANS IN JSP

        

 Java Beans

Java Beans are reusable components. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a class.

 JSP?s provide three basic tags for working with Beans.  

  • <jsp:useBean id=?bean name? class=?bean class?  scope = ?page | request | session |application ?/>

 bean name = the name that refers to the bean.

Bean class = name of the java class that defines the bean. 

  • <jsp:setProperty name = ?id? property = ?someProperty?  value = ?someValue? />

    id = the name of the bean as specified in the useBean tag.

property = name of the property to be passed to the bean.

value = value of that particular property .

An variant for this tag is the property attribute can be replaced by an  ? * ?. What this does is that it accepts all the form parameters and thus reduces the need for writing multiple setProperty tags. The only consideration is that the form parameter names should be the same as that of the bean property names.

  • <jsp:getProperty name = ?id? property = ?someProperty? />

Here the property is the name of the property whose value is to be obtained from the bean.

 BEAN SCOPES :

  These defines the range and lifespan of the bean.

    The different options are :

    • Page scope :

Any object whose scope is the page will disappear as soon as the current page finishes generating. The object with a page scope may be modified as often as desired within the particular page but the changes are lost as soon as the page exists.

By default all beans have page scope.

    • Request scope :

Any objects created in the request scope will be available as long as the request object is.  For example if the JSP page uses an jsp:forward tag, then the bean should be applicable in the forwarded JSP also, if the scope defined is of Request scope.

    • The Session scope :

In JSP terms, the data associated with the user has session scope. A session does not correspond directly to the user; rather, it corresponds with a particular period of time the user spends at a site. Typically, this period is defined as all the visits a user makes to a site between starting and existing his browser.

 The BEAN structure :

The most basic kind of bean simply exposes a number of properties by following a few simple rules regarding method names. The Java BEAN is not much different from an java program. The main differences are the signature methods being used in a bean. For passing parameters to a bean, there has to be a corresponding get/set method for every parameter. Together these methods are known as accessors.

 Eg. Suppose we want to pass a parameter ?name? to the bean and then return it in the capital form. In the bean, there has to be an setName() method and an corresponding getProperty() method.  A point to be noted is that the first letter of the property name is capitalized.(Here, N is in capital)

  Also, it is possible to have either get or set in a bean, depending on the requirement for a read only or a write only property. 

An example for a Database connection bean is as shown :  

package SQLBean;

import java.sql.*;  
import java.io.*;  

public class DbBean {

  String dbURL = "jdbc:db2:sample";
 
String dbDriver = "COM.ibm.db2.jdbc.app.DB2Driver"; 
 
private Connection dbCon;

  public DbBean(){  
   super();    
   }

  public boolean connect() throws ClassNotFoundException,SQLException{ 
 
Class.forName(dbDriver); 
 
dbCon = DriverManager.getConnection(dbURL); 
    return true; 
 
}

 

  public void close() throws SQLException{ 
 
dbCon.close(); 
  
}

  public ResultSet execSQL(String sql) throws SQLException{

  Statement s = dbCon.createStatement(); 
 
ResultSet r = s.executeQuery(sql); 
 
return (r == null) ? null : r; 
 
}

  public int updateSQL(String sql) throws SQLException{   
     Statement s = dbCon.createStatement();
  
int r = s.executeUpdate(sql);
  
return (r == 0) ? 0 : r; 
 
}

}
 

The description is as follows :

  This bean is packaged in a folder called as ?SQLBean?. The name of the class file of the bean is DbBean. For this bean we have hardcoded the Database Driver and the URL. All the statements such as connecting to the database, fetching the driver etc are encapsulated in the bean.

There are two methods involved in this particular bean :

Executing a particular query.

Updating a database.

The execSQL(String sql) method accepts the SQL query in the form of a string from the JSP file in which this bean is implemented.  

Then the createStatement() method initiates the connection with the dbCon  connection object.

Further the executeQuery(sql) method executes the query which is passed on as a string.

return (r == null) ? null : r ;

  What this statement does is that, if the value of r is null, it returns a null value and if it is a non null value, it returns the value of r. Though this statement seems redundant, it is useful for preventing any errors that might occur due to improper value being set in r.

The JSP Program is as shows :

<HTML>  
<HEAD><TITLE>DataBase Search</TITLE></HEAD>  
<BODY>

<%@ page language="Java" import="java.sql.*" %>  

<jsp:useBean id="db" scope="request" class="SQLBean.DbBean" />

<jsp:setProperty name="db" property="*" />

 <%!  
  
ResultSet rs = null ; 
  
ResultSetMetaData rsmd = null ; 
  
int numColumns ; 
  
int i;  
%>

<center>  
<h2> Results from </h2>  
<hr>  
<br><br>  
<table>

<% 
  
db.connect();

try { 
 
rs = db.execSQL("select * from EMPLOYEE");  
  i = db.updateSQL("UPDATE employee set FIRSTNME = 'hello world' where EMPNO='000010'"); 
 
out.println(i); 
 
}catch(SQLException e) { 
    throw new ServletException("Your query is not working", e);    
    }  

  rsmd = rs.getMetaData(); 
 
numColumns = rsmd.getColumnCount(); 
 
for(int column=1; column <= numColumns; column++){  
 
out.println(rsmd.getColumnName(column)); 
  
}  
%>

<% 
 
while(rs.next()) {  
%>    
<%= rs.getString("EMPNO") %>
<BR>  
<% 
 
}  
%>  
<BR>  
<%

   db.close();

%>

Done

</table>

</body>

</HTML>

 

The corresponding tags used in the JSP are as follows :

<jsp:useBean id="db" scope="request" class="SQLBean.DbBean" />

This tag specifies that the id of this bean is ?db?. This id is used throughout the page to refer to this particular bean. The scope of this bean is limited to the request scope only. The class attribute points to the class of the bean.

Here the class file is stored in the SQLBean folder.

<jsp:setProperty name="db" property="*" />

This property is used for passing on all the values which are obtained from the form. In this program, the SQL query can be passed on to the program as a part of the request.getParameter so that the query can be modified according to the requests.

rs = db.execSQL("select * from EMPLOYEE");

We can access the execSQL() method by using the bean id. Also the SQL is passed on to this method.

i = db.updateSQL("UPDATE employee set FIRSTNME = 'hello world' where EMPNO='000010'");

The updateSQL() method can also be used in the same JSP program. Here we are updating the employee table and resetting the FIRSTNME field where the EMPNO is 000010.

The major difference between an executeQuery and executeUpdate is that, an executeQuery returns the result set and an executeUpdate returns an integer value corresponding to the number of rows updated by the current query.

As can be seen, it is very easy to connect to databases using beans rather than writing the whole code over and over again in every JSP which requires to talk to the database.

    

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 30, 2005

Related Tutorials

Discuss: Using Beans in JSP. A brief introduction to JSP and Java Beans.   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:8
Altaf
May 24, 2011
java

Write a JSP page to display the number of hits to this page. (Hint: use application scope of java bean).
sleiman
May 25, 2011
java beans

it seams pointless . because it is the same as if we are using an object from this class. what is the main difference??!!
suyambu
June 16, 2011
Nice one

Very good explanation. it helps me lot....Thank you
???
March 19, 2013
Hi

Brilliant!
harish.k
January 17, 2012
update

import java.sql.Connection; import java.sql.Statement; import com.tcs.ilp.usermanagement.bean.StudentViewBean; import com.tcs.ilp.usermanagement.connection.ConnectionManager; public class StudentUpdateDAO { static Connection currentCon = null; public static StudentViewBean update(StudentViewBean bean) { //preparing some objects for connection Statement stmt = null; String email = bean.getEmail(); String address=bean.getAddress(); String mobileno=bean.getMobileno(); String username=bean.getUsername(); System.out.println(username); String s ="update student set email='"+email+"',address='"+address+"',mobileno='"+mobileno+"' where username='"+username+"'"; try { currentCon = ConnectionManager.getConnection(); stmt=currentCon.createStatement(); stmt.executeQuery(s); stmt.executeQuery("commit"); bean.setValid(true); } catch (Exception ex) { System.out.println("update failed: An Exception has occurred! " + ex); } finally { if (stmt != null) { try { stmt.close(); } catch (Exception e) {} stmt = null; } if (currentCon != null) { try { currentCon.close(); } catch (Exception e) { } currentCon = null; } } return bean; } }
Dr.James
January 26, 2012
JOB SEEKERS NEEDED URGENTLY

We are a reputable company and we have customers all over the world.Presently we are having some problems with our clients in India simply because we ve not yet open an office there.So right now we needed some people who can be working for us as an agent in India,which we have agreed to offer any of our workers 15% of any amount paid to him or her through any of our clients.All we need from you is be honest and transparency.We are looking forward to hear from you soon.
PARTHI
June 1, 2012
thanks

its easily undersatnd. thanks to explain in details.....
A.vinothkumar
August 1, 2012
Java

How to connect java with webapplication......
DMCA.com