Wednesday, March 10, 2010

USING BEANS IN JSP

Categories: , , ,


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 javaprogram. 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
<  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
 <  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") % > 


< %
                }
% >


Done
   
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.

Spread The Love, Share Our Article

Related Posts

No Response to "USING BEANS IN JSP"

Post a Comment