16
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 : o Page scope :

Java beans

Embed Size (px)

DESCRIPTION

That is java bean tutorial created to learn easily java beans within 20 minutes

Citation preview

Page 1: Java beans

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 :

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

o Request scope :

Page 2: Java beans

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.

o 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{ 

Page 3: Java beans

  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.

Page 4: Java beans

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()) {  %>    

Page 5: Java beans

<%= 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.

Page 6: Java beans

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.

The Page Directive in JSP Page

      

This section illustrates you about the page directive of the JSP page which works for the entire JSP page. These directives apply different properties for the page like language support, page information and import etc. by using the different attributes of the directives. There are three types of directives are as follows:

Page Directive Include Directive Taglib Directive

In this section, you will learn about the page directive and it's attributes and explanation one-by-one. This is the directive of the JSP page which defines the properties for the entire JSP page by using it's different attributes and set values of the attributes as per requirements.

Syntax of the declaration of the page directive with it's attributes is <%@ page attributeName="values" %>. The space between the tag <%@ and %> before the page (directive name) and after values of the last attribute, is optional, you can leave the space or not.

Following are name of the attributes of the page directive used in JSP:

language extends import session buffer autoFlush isThreadSafe info errorPage contentType isErrorPage pageEncoding isELIgnored

Page 7: Java beans

language: This is the attribute of the page directive of the JSP which is used for specifying some other scripting languages to be used in your JSP page but in this time, it's value is almost become java that is optional.

extends: This is the attributes of the page directive of the JSP which is used for specifying some other java classes to be used in your JSP page like packagename.classname. The fully qualified name of the superclass of the Java class will be accepted.

import: This attribute imports the java packages and it's classes more and more. You can import more than one java packages and classes by separating with comma (,). You can set the name of the class with the package name directly like packagename.classname or import all classes of the package by using packagename.*.

session: This attribute sets a boolean value either true or false. If the value of session attribute is true then the session object refers to the current or a new session because the client must be in the HTTP session for running the JSP page on the server. If you set the value of session object false then you can not use the session object or <jsp:useBean> element with scope="session" in JSP page. And then if a type of error occurs i.e. called the translation-time error. The default value of session attribute is true.

buffer: This attribute sets the buffer size in kilobytes i.e. used by the out object to handle output generated by the JSP page on the client web browser. If you specify the buffer size then the output will be buffered with at least 8kb because the default and minimum value of the buffer attribute is 8kb.

autoFlush: This attribute of the page directive supports for flushing buffer automatically when the buffer is full. The value of the autoFlush attribute is either true or false. If you will specify the true value then the buffer will be flushed otherwise it will generate a raised exception if you set the false value. You cannot set the false value if the buffer size is none.

isThreadSafe: This attribute support the facility of maintaining thread for sending multiple and concurrent requests from the JSP container to the JSP page if you specify the true value of the attribute otherwise if you specify the false value of the attribute then the JSP container can send only one request at one time. The default value of the attribute is true.

info: This attribute simply sets the information of the JSP page which is retrieved later by using Servlet.getServletInfo() method. The value of the attribute will be a text string.

errorPage: This attribute sets a url (relative path starting from the "/" which refers from the root directory of your JSP application). If any exception is generated the the attribute refers to the file which is mentioned in the given url. If you do not specify the url then the attribute refers to the current page of your JSP application if any exception generated.

isErrorPage: This attribute sets the boolean value either true or false. You can use the exception object in the JSP page if you set the true value of the attribute otherwise you cannot use the exception object because the default value of the attribute is false.

Page 8: Java beans

contentType: This attribute specifies the MIME type and the character encoding i.e. used for the JSP response. The default MIME type is "text/html" and the default character set is "ISO-8859-1". You can also specify other.

pageEncoding: This attribute specifies the language that the page uses when the page is sent to the browser. This attribute works like the meta tag of the HTML markup language.

isELIgnored: This is a boolean attribute that specifies either true or false value. If you set the attribute value is true then any type of the EL expressions will be ignored in the JSP page.

Code Description:

In the following program, <% and %> JSP tags. Java codes are written in between the both tag.

out.println("text"):Above is the method of the out object of the Java System class. This method takes a text string to be printed on the browser.

Here is the code of the program:

<%@page language="java" %><html>

<head><title>Hello World JSP Page.</title></head>

<body><font size="10"><%

String name="Roseindia.net";

out.println("Hello " + name + "!");

%></font>

</body></html>Output of the program:

The import Attribute of page Directive In JSP

      

This section shows you how to import a java package or the class in your jsp application. Here a Java code has also been provided which class has been imported in the following JSP code like <%@page import="roseindia.Extends" %> in which, the import is the attribute of the page directive in JSP and the value of the attribute is the "roseindia.Extends". Here, roseindia is the

Page 9: Java beans

package name and the Extends is the class which is made after compilation of the Extends.java file. This class file is contained by the folder which determines the package name. And the package name folder is putted in the classes folder inside the <your application root directory>/WEB-INF/classes/package_name.

Basically, this attribute of the page directive imports the java packages and it's classes more and more. You can import more than one java packages and classes by separating with comma (,). You can set the name of the class with the package name directly like packagename.classname or import all classes of the package by using packagename.*.

Here is the code of the program:

<%@page import="roseindia.Extends" %><html> <head><title>Example of Extends Attribute of page Directive in JSP</title></head>

<body> <font size="20" color="red"> <%

Extends ex = new Extends();out.print(ex.show());

%> </font> </body></html>

Here is the code of Extends.java file:package roseindia;

public class Extends{  public String show(){  return "Roseindia.net";  }

}

The session Attribute of page Directive In JSP

      

This section provides you the best illustration of the session attribute of the page directive in JSP. This is the boolean attribute of the directive. It sets a boolean value either true or false. If the value of session attribute is true then the session object refers to the current or a new session

Page 10: Java beans

because the client must be in the HTTP session for running the JSP page on the server. If you set the value of session object false then you can not use the session object or <jsp:useBean> element with scope="session" in JSP page. And then if a type of error occurs i.e. called the translation-time error. The default value of session attribute is true.

There are four pages have been provided for understanding the session attribute of the page directive of JSP. These are:

sessionForm.jsp session.jsp sessionresult.jsp ShowFalseSession.jsp

First you have to run the sessionForm.jsp page on the server and get the value of username field and the password field if any and set the session objects (username and password) with the retrieved value of those and show the session.jsp page with Welcome message with the username. This page retrieves the value of username and the password field by using the request.getParameter() method and set these values to the session object that is retrieved later in the sessionresult.jsp page for showing the welcome message with username by getting the session value. The sessionresult.jsp page contains the page directive which attributed session has been set the true value for the session operation. But when you click on the another link ("Next Page with session false.") made on the session.jsp page then the ShowFalseSession.jsp page will be seen with the message "The value of session object is false!" because when the value of the session attribute of the page directive is false then the page does not support any type of session operations in the page.

Here is the code of the sessionForm.jsp page:

<html> <head><title>Disable Session Environment.</title></head> <body> <form action="session.jsp" method="post">

<table border="0" cellspacing="0" cellpadding="0"> <tr> <td>User Name: </td> <td><input type="text" size="20" name="txtUserName" /> </tr> <tr> <td>Password: </td> <td><input type="password" size="20" name="txtPassword" /> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit" name="B1" /></td> </tr></table>

</form> </body></html>

Page 11: Java beans

Output for the sessionForm.jsp page:

Here is the code of the session.jsp page:

<%@page language="java" %> <%

String userName = request.getParameter("txtUserName");String password = request.getParameter("txtPassword");if(userName == null)

userName = "";if(password == null)

password = ""; if(!userName.equals("") && !password.equals("")){

session.setAttribute("SessionUser", userName);session.setAttribute("SessionPassword", password);out.println("Welcome " + userName + "!");out.println("<br/><a href=sessionresult.jsp>

Next Page with session true.</a>");out.println("<br/><a href=ShowFalseSession.jsp>

Next Page with session false.</a>");}else if(userName.equals("")){

out.println("<font color=red><b>User name required.</b></font>");

out.println("<br/><a href=sessionForm.jsp>Go back!</a>");}else if(password.equals("")){

out.println("<font color=red><b>Password required.</b></font>");

out.println("<br/><a href=sessionForm.jsp>Go back!</a>");}

%>

Page 12: Java beans

Output for the session.jsp page:

Above image shows the output when you submit the form in the sessionForm.jsp page without entering the username and if you do not enter the password and submit the form then the output will be seen as:

If you click on the link ("Go back") then the sessionForm.jsp will be loaded. If you enter the username and password then the session.jsp page will be seen as:

In the above output if you click on the first link ("Next Page with session true.") then the sessionresult.jsp page will be opened otherwise the ShowFalseSession.jsp page will be seen if you click on the another link ("Next Page with session false.").

Here is the code of the sessionresult.jsp page:

<%@page language="java" session="true" %> <%

String username = (String)session.getAttribute("SessionUser");String password = (String)session.getAttribute("SessionPassword");out.println("<b>Welcome " + username + "!</b>");

%>

Output for the sessionresult.jsp page:

Here is the code of the ShowFalseSession.jsp page:

<%@page language="java" session="false" %> <%

out.println("The value of session attribute is false!");%>

Output for the ShowFalseSession.jsp page:

Page 13: Java beans