SlideShare a Scribd company logo
1 of 12
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 :
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{
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.


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

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.

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

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>");
        }
%>

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:

More Related Content

What's hot

Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_javaardnetij
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3IMC Institute
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicIMC Institute
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in MagentoDivante
 
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Ryan Mauger
 
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Using SP Metal for faster share point development
Using SP Metal for faster share point developmentUsing SP Metal for faster share point development
Using SP Metal for faster share point developmentPranav Sharma
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)Craig Dickson
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Jsp standard tag_library
Jsp standard tag_libraryJsp standard tag_library
Jsp standard tag_libraryKP Singh
 

What's hot (19)

Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_java
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Database Connection Pane
Database Connection PaneDatabase Connection Pane
Database Connection Pane
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in Magento
 
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
 
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
(국비지원학원/재직자교육/실업자교육/IT실무교육_탑크리에듀)#4.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)
 
Using SP Metal for faster share point development
Using SP Metal for faster share point developmentUsing SP Metal for faster share point development
Using SP Metal for faster share point development
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Jsp standard tag_library
Jsp standard tag_libraryJsp standard tag_library
Jsp standard tag_library
 

Similar to Java beans (20)

Java jdbc
Java jdbcJava jdbc
Java jdbc
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Lecture17
Lecture17Lecture17
Lecture17
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
JDBC
JDBCJDBC
JDBC
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 

Recently uploaded

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 

Recently uploaded (20)

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 

Java beans

  • 1. 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 :
  • 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 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{
  • 3. 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 ;
  • 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 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>
  • 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 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.
  • 6. 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 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.
  • 7. 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. 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.
  • 8. 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 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.
  • 9. 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 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.
  • 10. 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> Output for the sessionForm.jsp page:
  • 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 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>"); } %> Output for the session.jsp page:
  • 12. 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: