Java beans


Published on

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

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java beans

  1. 1. Java BeansJava Beans are reusable components. They are used to separate Business logic from the Presentationlogic. 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 thatit 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 beanproperty 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 :
  2. 2. 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 fewsimple 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 passingparameters 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 thecapital form. In the bean, there has to be an setName() method and an correspondinggetProperty() method. A point to be noted is that the first letter of the property name iscapitalized.(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 awrite only property.An example for a Database connection bean is as shown :package SQLBean;import java.sql.*;import*;public class DbBean { String dbURL = "jdbc:db2:sample"; String dbDriver =""; private Connection dbCon; public DbBean(){ super(); } public boolean connect() throwsClassNotFoundException,SQLException{
  3. 3. Class.forName(dbDriver); dbCon = DriverManager.getConnection(dbURL); return true; } public void close() throws SQLException{ dbCon.close(); } public ResultSet execSQL(String sql) throwsSQLException{ Statement s = dbCon.createStatement(); ResultSet r = s.executeQuery(sql); return (r == null) ? null : r; } public int updateSQL(String sql) throwsSQLException{ 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 isDbBean. For this bean we have hardcoded the Database Driver and the URL. All the statements such asconnecting 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 whichthis 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 ;
  4. 4. What this statement does is that, if the value of r is null, it returns a null value and if it is a non nullvalue, it returns the value of r. Though this statement seems redundant, it is useful for preventing anyerrors 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 worldwhere 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.getString("EMPNO") %><BR>
  5. 5. <% }%><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 tothis particular bean. The scope of this bean is limited to the request scope only. The classattribute 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, theSQL query can be passed on to the program as a part of the request.getParameter so that the query can bemodified according to the = 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 whereEMPNO=000010");The updateSQL() method can also be used in the same JSP program. Here we are updating the employeetable and resetting the FIRSTNME field where the EMPNO is 000010.The major difference between an executeQuery and executeUpdate is that, an executeQuery returns theresult set and an executeUpdate returns an integer value corresponding to the number of rows updated bythe current query.
  6. 6. As can be seen, it is very easy to connect to databases using beans rather than writing the whole code overand over again in every JSP which requires to talk to the database.The Page Directive in JSP PageThis section illustrates you about the page directive of the JSP page which works for the entireJSP page. These directives apply different properties for the page like language support, pageinformation and import etc. by using the different attributes of the directives. There are threetypes of directives are as follows: Page Directive Include Directive Taglib DirectiveIn this section, you will learn about the page directive and its attributes and explanation one-by-one. This is the directive of the JSP page which defines the properties for the entire JSP page byusing its different attributes and set values of the attributes as per requirements.Syntax of the declaration of the page directive with its attributes is <%@ pageattributeName="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 isELIgnoredlanguage: This is the attribute of the page directive of the JSP which is used for specifying someother scripting languages to be used in your JSP page but in this time, its value is almost becomejava that is optional.
  7. 7. extends: This is the attributes of the page directive of the JSP which is used for specifying someother java classes to be used in your JSP page like packagename.classname. The fully qualifiedname of the superclass of the Java class will be accepted.import: This attribute imports the java packages and its classes more and more. You can importmore than one java packages and classes by separating with comma (,). You can set the name ofthe class with the package name directly like packagename.classname or import all classes ofthe package by using packagename.*.session: This attribute sets a boolean value either true or false. If the value of session attribute istrue then the session object refers to the current or a new session because the client must be inthe HTTP session for running the JSP page on the server. If you set the value of session objectfalse then you can not use the session object or <jsp:useBean> element with scope="session" inJSP page. And then if a type of error occurs i.e. called the translation-time error. The defaultvalue of session attribute is true.buffer: This attribute sets the buffer size in kilobytes i.e. used by the out object to handle outputgenerated by the JSP page on the client web browser. If you specify the buffer size then theoutput will be buffered with at least 8kb because the default and minimum value of the bufferattribute is 8kb.autoFlush: This attribute of the page directive supports for flushing buffer automatically whenthe buffer is full. The value of the autoFlush attribute is either true or false. If you will specifythe true value then the buffer will be flushed otherwise it will generate a raised exception if youset 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 andconcurrent requests from the JSP container to the JSP page if you specify the true value of theattribute otherwise if you specify the false value of the attribute then the JSP container can sendonly one request at one time. The default value of the attribute is This attribute simply sets the information of the JSP page which is retrieved later by usingServlet.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 rootdirectory of your JSP application). If any exception is generated the the attribute refers to the filewhich is mentioned in the given url. If you do not specify the url then the attribute refers to thecurrent page of your JSP application if any exception generated.isErrorPage: This attribute sets the boolean value either true or false. You can use the exceptionobject in the JSP page if you set the true value of the attribute otherwise you cannot use theexception object because the default value of the attribute is false.contentType: This attribute specifies the MIME type and the character encoding i.e. used for theJSP response. The default MIME type is "text/html" and the default character set is "ISO-8859-1". You can also specify other.
  8. 8. pageEncoding: This attribute specifies the language that the page uses when the page is sent tothe 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 theattribute 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 stringto be printed on the browser.Here is the code of the program:<%@page language="java" %><html> <head><title>Hello World JSPPage.</title></head> <body> <font size="10"> <% Stringname=""; out.println("Hello " +name + "!"); %> </font> </body></html>Output of the program:The import Attribute of page Directive InJSPThis section shows you how to import a java package or the class in your jsp application. Here aJava 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 pagedirective in JSP and the value of the attribute is the "roseindia.Extends". Here, roseindia is thepackage name and the Extends is the class which is made after compilation of the Extends.javafile. This class file is contained by the folder which determines the package name. And thepackage name folder is putted in the classes folder inside the <your application rootdirectory>/WEB-INF/classes/package_name.
  9. 9. Basically, this attribute of the page directive imports the java packages and its classes more andmore. 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.classnameor 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 ExtendsAttribute of page Directive inJSP</title></head> <body> <font size="20" color="red"> <% Extends ex = new Extends(); out.print(; %> </font> </body></html>Here is the code of file:package roseindia;public class Extends{ public String show(){ return ""; }}The session Attribute of page Directive InJSPThis section provides you the best illustration of the session attribute of the page directive inJSP. This is the boolean attribute of the directive. It sets a boolean value either true or false. Ifthe value of session attribute is true then the session object refers to the current or a new sessionbecause the client must be in the HTTP session for running the JSP page on the server. If you setthe 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 thetranslation-time error. The default value of session attribute is true.
  10. 10. There are four pages have been provided for understanding the session attribute of the pagedirective of JSP. These are: sessionForm.jsp session.jsp sessionresult.jsp ShowFalseSession.jspFirst you have to run the sessionForm.jsp page on the server and get the value of username fieldand the password field if any and set the session objects (username and password) with theretrieved value of those and show the session.jsp page with Welcome message with theusername. This page retrieves the value of username and the password field by using therequest.getParameter() method and set these values to the session object that is retrieved laterin the sessionresult.jsp page for showing the welcome message with username by getting thesession value. The sessionresult.jsp page contains the page directive which attributed session hasbeen set the true value for the session operation. But when you click on the another link ("NextPage with session false.") made on the session.jsp page then the ShowFalseSession.jsp page willbe seen with the message "The value of session object is false!" because when the value of thesession attribute of the page directive is false then the page does not support any type of sessionoperations 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>Output for the sessionForm.jsp page:
  11. 11. 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 namerequired.</b></font>"); out.println("<br/><a href=sessionForm.jsp>Go back!</a>"); } else if(password.equals("")){ out.println("<font color=red><b>Passwordrequired.</b></font>"); out.println("<br/><a href=sessionForm.jsp>Go back!</a>"); }%>Output for the session.jsp page:
  12. 12. Above image shows the output when you submit the form in the sessionForm.jsp page withoutentering the username and if you do not enter the password and submit the form then the outputwill be seen as:If you click on the link ("Go back") then the sessionForm.jsp will be loaded. If you enter theusername 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 thesessionresult.jsp page will be opened otherwise the ShowFalseSession.jsp page will be seen ifyou 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: