Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
JSP
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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.

      

                          

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

14 comments so far (post your own) View All Comments Latest 10 Comments:

awesome tutorial

Posted by robby fowler on Monday, 04.21.08 @ 09:45am | #57376

This is an awesome tutorial

Posted by javaseek on Wednesday, 03.19.08 @ 23:44pm | #53402

Very very comfortable material for beginners as well as for programmers.very good site. i have no words to tell about this site

Posted by nagapriya on Wednesday, 01.30.08 @ 13:43pm | #46581

hi i wanna download JSP tutorials provided by roseindia.net .Is there any lnk to download to download this tutorials .
thnnks n regards
vikam singh

Posted by vikram on Monday, 12.24.07 @ 11:31am | #43549

Try to provide me uptates about given in the titla

Posted by mukesh kumar on Thursday, 12.20.07 @ 13:33pm | #43091

USING BEANS IN JSP program how can we get Driver and url from web.xml

Posted by Ramakrishna K.V on Tuesday, 12.18.07 @ 17:04pm | #42832

this is excelent tutorials

Posted by surya on Tuesday, 10.9.07 @ 17:02pm | #32944

the tutorial is very good for the beginners...
very nice explanations have been given...

Posted by SharadhaAnanth on Friday, 10.5.07 @ 12:44pm | #31794

how to associate a bean to a text box, radio button, drop down menu .

Posted by kuldeep on Thursday, 07.26.07 @ 10:37am | #21970

It's examples are best, for those who are starting from premitive stage, and want to understand from deep.

Posted by jeet on Friday, 07.6.07 @ 12:29pm | #20822

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.