Java Web Technology Unit-5 by whiteshadow1


                                JAVA SERVER PAGES (JSP)
            Java Server Pages, also known as JSP, are a simple but powerful technology used to generate
dynamic HTML on the server side. It provides a way to separate content generation from content
presentation. It an extension of servlet technology not a replacement. It mapped with *.jsp extension.
JSP allows for the direct insertion of servlet code into an static HTML file. Each block of servlet code
(also called a scriplet ) is surrounded by a leading <% tag and a closing %> tag.

<% out.println (“HELLO JSP WORLD”); %>

Note: Embedding the Java code in an HTML File.=JSP.


        To process a Java server pages (JSP) file, we need a JSP container or a JSP Engine which is
installed in web server or application server. These servers are used to run the jsp page. Whenever a
client request a JSP page through a browser to the webserver. The web server reads the URL from the
web browser and recognizes the .jsp extension in the URL and understands the request is made for Java
server page. Then the web server passes the request to the JSP Engine / JSP Container. Then the JSP
Engine translates the JSP file into a Servlet (TRANSLATION UNIT).Then the Servlet is recompiled
into a Java class (COMPILATION UNIT).This Translation and compilation phase occurs only when
the JSP file is requested for the first time.

                                                                                    Java Class
        JSP page          Translated            Servlet Code        Compiled             file
          (.jsp)              To                 (.Java File)        To             (.class File)

Note : A JSP Container/JSP Engine Contains the Jasper(jspc) used to compile the JSP file


      JSP is new technology used to develop the dynamic web application.
      JSP Enables programmers to separate the dynamic contents from static contents.
      JSP is Java based technology which is recompiled to generate the servlet code of equivalent JSP
       file for processing the request.
      JSP includes in built support for HTTP session management.
      It allows to create customs tags.
      It can be integrated with the EJB API’s.
      JSP is not a replacement for servlets. Rather, JSP technology and servlets together provide an
       attractive solution to web scripting/programming by offering platform independence, enhanced
       performance, and separation of logic from display, ease of administration, extensibility into the
       enterprise, and most importantly, ease of use.

The Anatomy of JSP Page or Components of JSP Page

   Java Server Pages are combination of standard HTML and scripting tags. The JSP is compiled and
created into a servlet. The resulting servlet consists of HTML and scripting new tags(<% … %> ) for
generating the dynamic contents. The HTML in a JSP page is not processed by the Container, Only the
scripting code is processed by the container. Hence the JSP Page is divided into two categories.
   1) JSP Elements: Elements that are processed on the server.
   2) Template: These are the static portion of jsp file that are ignored by the server.
The elements are further divided into three categories .1.Directives 2.Scripting Elements 3.Action

   1. Directives: Directives are JSP elements that provide global information about an entire JSP
       page. The syntax of a directive is as follows:
                                <%@ directive {attribute="value"} %>
       This states that, for this page directive, assign these values for these attributes. A directive can
contain n number of optional attribute/value pairs. There are three possible directives currently defined
by the JSP specification: page, include, and taglib.

   1.1. The page directive: The page directive defines information that will be globally available for
        that Java Server Page. These page level settings will directly affect the compilation of the JSP.
                    Attributes                                                Definition
language="scripting Language"                          This attribute tells the server what language will be
                                                       used to compile the JSP file. Currently Java is the
                                                       only available language.
extends="class Name"                                   This attribute defines the parent class that the JSP
                                                       generated servlet will extend from.
import="import List"                                   This attribute defines the list of packages that will
                                                       be available to this JSP.
session="true | false"                                 This attribute determines whether the session data
                                                       will be available to this page. The default is true.
buffer="none|size in kb"                               This attribute determines whether the output
                                                       stream is buffered. The default value is 8KB.
autoFlush ="true|false"                                This attribute determines whether the output
                                                       buffer will be flushed automatically.
isThreadSafe="true|false"                              This attribute tells the JSP engine that this page
                                                       can service more than one request at a time. By
                                                       default this value is true; if false, the
                                                       SingleThreadModel is used.
errorPage="error_url"                                  This attribute represents the relative URL to the
                                                       JSP page that will handle exceptions.
isErrorPage="true|false"                               This attribute states whether or not the JSP page is
                                                       errorPage. The default is false.
contentType="ctinfo"                                   This attribute represents the MIME type and
                                                       character set of the response.

       1.2 The include directive : The include directive is used to insert text and code at JSP
translation time. The syntax of the include directive is as follows:

                                <%@ include file="relativeURLspec" %>

The file that the file attribute points to can reference a normal text HTML file or it can reference a JSP
file, which will be evaluated at translation time.

       1.3 The taglib directive : The taglib directive declares that the page uses custom tags, uniquely
names the tag library defining them, and associates a tag prefix that will distinguish usage of those tags.
The syntax of the taglib directive is as follows:

                         <%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>

The uri attribute references a URI that uniquely names the set of custom tags.
The prefix attribute defines the prefix string used to distinguish a custom tag instance.

   2. Scripting elements : JSP scripting is a mechanism for embedding The Java code fragments
       directly into an HTML page. There are three types of scripting elements:
     Declarations
     Expression
     Scriptlets
Before we discuss scripting elements we will discuss the implicit JSP objects
Implicit Objects in JSP:-Implicit variables or objects are automatically available to a JSP file.

  Object                                         Description                                 Scope
application Represents     the     servlet     context     returned    from a    call  to Application
Config      Represents the Servlet Config for this JSP                                    Page
Out         Represents the JspWriter object to the output stream                          Page
request     Represents the request object that triggered the request.                     Request
response    Represents the response object that triggered the request.                    Page
session     Represents the session object, if any, created for the client during an HTTP Session
pageContext Represents the page context for the JSP                                       Page
Page        Represents the this object for this instance of the JSP                       Page

    2.1 Declarations: JSP declarations are used to declare variables and methods in the scripting
language used in a JSP page. JSP declarations are initialized when the JSP page is initialized The syntax
for a JSP declaration is as follows:
                                           <%! declaration %>

A sample variable declaration using this syntax is declared here:

     <%! String name = new String ("BOB"); %>

       2.2 Expressions : JSP expressions are elements in a scripting language that are evaluated with
the result being converted to a java.lang.String. After the string is converted, it is written to the current
out JspWriter object. JSP expressions are evaluated at HTTP request-time,
The syntax of a JSP expression is as follows:

                                           <%= expression %>

A code snippet containing a JSP expression is shown here:

       <%! String name = new String("BOB"); %>
       <%! public String getName() { return name; } %>
       Hello <B><%= getName() %></B>
       The Sum <B> <%= (3+4) %>
    </BODY>                                                              O/P: Hello: BOB
  </HTML>                                                                    The Sum: 7

       2.3 Scriptlets: Scriptlets provide the ability to directly insert java code into an HTML document.
The syntax of a JSP scriptlet is listed as follows:

                                            <% “java code” %>

An example scriptlet, using the request and out variables.

    <%@ page language=”java” %>
     <% out.println (“Your address is:” + request.getRemoteAddr()); %>
 O/P: Your address is:

   3. Action Elements: The action elements are XML tags that can be in JSP page used to access the
       java bean in a page.JSP action elements get executed when JSP page makes some request.The
       action elements are used to handle the dynamic actions that take place at runtime. JSP defines
       three types of actions.
               3.1 Standard Action
               3.2 JSP Standard Tag Library(JSTL)
               3.3 Custom Action
3.1 Standard Action: The actions are defined by the JSP specification itself.
i) <jsp:useBean> : It associates an instance of a JavaBean defined with a given scope and ID via a
newly declared scripting variable of the same ID.
<jsp:useBean id="name" scope="page|request|session|application"
       class=”class name” beanName="beanName" type="typeName" >

id : This attribute represents the identity of the instance of the object in the specified scope.
scope : The scope attribute represents the life of the object. The scope options are page, request,
session, and application.

class : The fully qualified class name that defines the implementation of the object. The class name is
case sensitive.
beanName : This attribute references the name of the bean, as expected to be instantiated by the
instantiate() method of the java.beans.Beans class.
type : The type attribute specifies the type of scripting variable defined.

ii) <jsp:setProperty> : The second standard action to help integrate JavaBeans into JSPs is
<jsp:setProperty>. It sets the value of a bean's property. The syntax is as follows

                  <jsp: setProperty name="beanName" property=”property_ name” />

       Here, the name attribute specifies the bean instance defined in <jsp:useBean> Property attribute
specifies the property of the bean for which you set a value. If the property value is (*) it sets all the
properties of the bean at a time.

iii) <jsp:getProperty> : It takes the value of the referenced bean instance's property, converts it to a
java.lang.String, and places it into the implicit out object.
                     <jsp:getProperty name="name" property="propertyName" />

iv) <jsp:include> :The <jsp:include> action provides a mechanism for including additional static
HTML and dynamic (JSP) resources in the current JSP page. The syntax for this action is as follows:
                             <jsp:include page="urlSpec" flush="true" />

v) <jsp:forward> : The <jsp:forward> action enables the JSP engine to dispatch, at runtime, the current
request to a static resource, servlet, or another JSP. The appearance of this action effectively terminates
the execution of the current page.
                                <jsp:forward page="relativeURLspec" />

vi) <jsp:param> :The <jsp:param> action is used to provide tag/value pairs of information, by
including them as subattributes of the <jsp:include>, <jsp:forward>, and the <jsp:plugin> actions. The
syntax as follows.
     <jsp:param name="paramName" value="paramValue">

vii) <jsp:plugin> : The <jsp:plugin> action gives a JSP author the ability to generate HTML that
contains the appropriate client-browser–dependent constructs, for example, OBJECT or EMBED, that
will result in the download of a Java plug-in and subsequent execution of the specified applet or
JavaBeans component. The syntax is as follows:
<jsp:plugin type="pluginType" code="classFile" codebase="relativeURLpath">

Example for <jsp:include> action

                                       1. index.jsp
<%@ page language="java" contentType="text/html"%>
<head><title>Royal Online Shopping </title>
<body bgcolor="#408080">
<table width="100%" height=”100%” border="0" cellspacing="3" bgcolor="#CEA953">
    <td colspan="2">
     <jsp:include page="top.jsp" />
 <tr height="70%">
   <td align="top" bgcolor="#E9E37C" rowspan="2">
           <jsp:include page="left.jsp" />
         <td align="main" bgcolor="#C2C287">
            <jsp:include page="main.jsp"/>
   <td colspan="3">
           <jsp:include page="marquee.html"/>

                                   2. top.jsp

<table border="0" width="100%" cellspacing="0" cellpadding="0" bgcolor="#FFCCCC">
  <td height="84">
   <img src="feroz.jpg" alt="logo" width="100" height="77"/>
        <td align="center">
        <font type="bold" size="6" color="red">SIM - ONLINE SHOPPING CENTER....</FONT>

                                  3. left.jsp

<div align="left" bgcolor="#33CCFF">
<input name="search" type="text" id="search" size="8"/>
<input name="search" type="submit" value="search"/><br />
<p>Product Catalog : </p>
 <li><a href="Mobiles.html">Mobiles</a></li>
 <li><a href="Computers.html">Computers</a></li>
 <li><a href="Book.html">Books</a></li>
 <li><a href="Electronics.html">Electronics</a></li>

                                    4. main.jsp
<center><strong>Please Authenticate <br>
<table width="50%" height="78" border="1" align="center" bgcolor="#FFCCFF">
   <th width="114" height="39" align="center"><strong>User Name</strong></th>
    <th width="101" scope="col"><input type="text" name="textfield"
      style="background-color='#FFFF99' "/></th>
    <td height="24" align="center" ><strong>Password</strong></td>
    <td><input name="password" type="password" id="password"
     style="background-color='#FFFF99' "/></td>
   <input type="submit" name="Submit" value="Submit" style="cursor:pointer" />

                                  5. marquee.html
<div align="center">
<font color="#9D7B2D" size="8">
 <Marquee>Welcome to <i>SIM<i> Online Shopping...By FEROZ KHANANI..</marquee>


Deployment of java beans in a JSP page/ generating a Dynamic web page using standard actions.

package beans.feroz;
public class BeanExample
        String name,branch;
        int rollNum;
        public void setName(String name)
        public void setBranch(String branch)
        public void setRollNum(int rollNum)
        public String getName()
        public String getBranch()
                return this.branch;
        public int getRollNum()
                return this.rollNum;
Access The Bean properties using <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty> actions.


<body bgcolor="#FFCCFF">
<form method="post">
<table width="50%" border="1">
   <td>Name:</td><td><input type="text" name="name"></td>
  <td>Branch:</td><td><input type="text" name="branch"></td>
   <td>RollNumber:</td><td><input type="text" name="rollNum"></td>
<input type="submit" value="Submit">
<jsp:useBean id="bean" class="beans.feroz.BeanExample"/>
<jsp:setProperty name="bean" property="*"/>// ’* ‘ denotes all the properties
<h2>You Entered :</h2>
<table border="1" bgcolor="pink" width="50%">
   <th>Name :</th>
   <td> <jsp:getProperty name="bean" property="name"/></td>
  <th>Branch :</th>
  <td><jsp:getProperty name="bean" property="branch"/></td>
 <th>RollNumber :</th>
 <td><jsp:getProperty name="bean" property="rollNum"/></td>


Demonstration of Scripting Elements (Directives, Expression, Scriptlets)

<%@ page language="java" session="false" %>
<%@ page import ="java.util.Date" %>
 <body bgcolor="#99cccc">
   <center><br><br><br><h2>The Current Time :
         Date date = new Date();
        <br><h2>Remote Address :
   <h2>The Expression (10+14) : <%= (10+14) %>

Example for Conditional processing using JSP scriptlets

<body bgcolor="#99cccc">
<form method="post">
 Name : <input type="text" size="15" name="name">
 <input type="submit" value="submit">
String name=(String)request.getParameter("name");
if(name=="" || name==null)
        out.println("<h2>Please Enter Your Name");
 out.println("<h2>Hello, "+name+"</h2>");

Demonstration of declaration Variable, Methods and Expression

<%@ page language="java" session="false" %>
<%@ page info="Written By Md Feroz" %>
  <body bgcolor="#99cccc">
   <h1>Demonstration of Declaration and Expression</h1><hr>
<%! String name="MD FEROZ"; %>
<%! int roll=1214;%>
<%! int m1=80,m2=77;%>
public double getAverage()
   return (m1+m2)/2;
 <h2>NAME : <em><%= name %> </em>
 <h2>ROLLNUMBER: <em><%= roll %></em>
 <h2>TOTAL MARKS : <em><%= (m1+m2) %></em>
 <h2>THE AVERAGE: <em><%= getAverage() %></em>

3.2 JSP Standard Tag Library (JSTL): JSP uses JSTL for performing some common tasks such as
condition execution, loop execution, data processing and so on. It allows a programmer to embed the
logic in JSP page without using JAVA code. The tag library uses some standard set of tags to perform
common operations. The following are the different types of JSTL tags – core, xml, sql, formatting and
   c: core              fmt:formatting           fn: fnction                   x:xml
   c:catch              fmt:bundle               fn:contains()                 x:choose
   c:choose             fmt:formatDate           fn:containsIgnoreCase()       x:forEach
   c:forEach            fmt:formatNumber         fn:endsWith()                 x:if
   c:forTokens          fmt:message              fn:escapeXml()                x:otherwise
   c:if                 fmt:param                fn:indexOf()                  x:out
   c:import             fmt:parseDate            fn:join()                     x:param
   c:otherwise          fmt:parseNumber          fn:length()                   x:parse
   c:out                fmt:requestEncoding      fn:replace()                  x:set
   c:param              fmt:setBundle            fn:split()                    x:transform
   c:redirect           fmt:setLocale            fn:startsWith()               x:when
   c:remove             fmt:setTimeZone          fn:substring()
   c:set                fmt:timeZone             fn:substringAfter()
   c:url                                         fn:substringBefore()
   c:when                                        fn:toLowerCase()

Program-1: <c:out>, <c:set>, <c:if> tags
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="" %>
<body bgcolor="pink">
<form method="post" action="firstJSTL.jsp">
 <select name="department" align ="center">
  <option value="">select</option>
  <option value="Computer Science">Computer Science
  <option value="Information Technology">Information Technology
  <option value="Electrical Engneering">Electrical Engneering
  <option value="Electronics communication Engneering">Electronics communication Engneering
  <option value="Mechanical Engneering">Mechanical Engneering

<input type="submit" value="submit">
 <c:set var ="dept" value="${param.department}"/>

<c:if test="${dept=='Computer Science'}">
     You selected <strong><c:out value="${dept}"/></strong> branch to Join !!!

<c:if test="${dept=='Information Technology'}">
  You selected <strong><c:out value="${dept}"/></strong> branch to Join !!!

<c:if test="${dept=='Electrical Engneering'}">
   You selected <strong><c:out value="${dept}"/></strong> brancn to Join !!!

<c:if test="${dept=='Electronics communication Engneering'}">
  You selected <strong><c:out value="${dept}"/></strong> branch to Join !!!

<c:if test="${dept=='Mechanical Engneering'}">
   You selected <strong><c:out value="${dept}"/></strong> baranch to Join !!!

 we can also select any item either by using <c:choice> tag or <c:otherwise> tag as follows

......... ... .....
     <c:when test=”${dept = =’Computer Science’}”>
       You selected <strong><c:out value="${dept}"/></strong> brancn to Join !!!
  select the other branch ! ! !
  ...... ... ......

Program-2 : <c:forEach> tag

<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="" %>
<body bgcolor="pink">
<% pageContext.setAttribute("names",new String[]{"MD Feroz Khanani","Simran Khanani"}); %>
<b>The List of Names are......</b>
<c:forEach var="i" items="${names}" varStatus="n">

   <c:out value="${n.index}"/>
   <c:out value="${n.current}"/>

Program-3: <c:forEach> tag

<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="" %>
<body bgcolor="pink">
<b>The Natural numbers are......</b>
<c:forEach var="i" begin="1" end="10">
   <c:out value="${i}"/>

Program-4 : <c:forTokens> tag

<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="" %>
<c:set var="i" value="MD Feroz;1214;Simran Khanani;7017;"/>
<body bgcolor="pink">
<table border="2">
   <th> Name </th>
   <th> Emp ID </th>
  <c:forTokens items="${i}" delims=";" var="tok">
  <td><c:out value="${tok}"/></td>

Program-5: <c:import> tag
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="" %>
 <body bgcolor="pink">
  <c:import url="names.html"/>
   <c:out value="Thank You for visitiong SIM site......."/>

Program-6 :<c:redirect> tag

<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="" %>
<c:set var="i" value="MD Feroz;1214;Simran Khanani;7017;"/>
 <body bgcolor="pink">
  <c:redirect url="http://localhost:8080/jstl/examples/names.html"/>
  <c:out value="This line will not be displayed on the screen…” />

JSTL EL: TJSTL stands for the Java Server Pages Standard Tag Library. This library provides a set of
XML-tags which provide Java programming functionality delivered by the tags along with expressions
created in the unimaginatively named United Expression Language, or EL. The goal of JSTL is to
minimize or, if possible, eliminate actual Java code introduced through JSP. It is used within the {…}
braces with a prefix $.
 <form action=”ELDemo.jsp”>
 <input type=”text” name=”name” value=”SIMRAN PUBLICATION”/>
 <input type=”submit” value=”submit”/>

<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="" %>
 <body bgcolor="pink">
 You entered : <b><c:out value=”${}”/></b>

Handling the Errors and Debugging in the JSP Page
  Whenever you are writing a JSP code, errors can occurs at different parts of the code. Since JSP code
is made up of so many separate Elements. Some of the possible errors occur in the following.
      Coding in JavaBeans or Java Classes.
      Errors in JSP Directives , Scripting Elements and Standard Actions.
      Within JSTL and EL.
      Within Template data.
                           Errors occur in JavaBeans and Java Classes

JSP uses the JavaBeans to transport the data between the JSP pages in a web application. Java Beans are
written in JAVA language, any syntax error occurs while writing the JavaBeans or when running the
compiled Java classes (Exceptions).

                                         Errors in Scripting Elements

Like JavaBeans scripting code is also written in Java language within the scriptlets (page, include,
taglib). (<% …%> ) The Java code is compiled and executed with other JSP page. This typically occurs
when a request is made for a JSP page.

**The First Example shows a TOMCAT displays a ERROR message status 500 when an error occurs in
JSP page.

      <%@ page language="java" session="false" >//not closed ‘%> ‘Properly
      <%@ page import ="java.util.Date" %>
       <body bgcolor="#99cccc">
         <center><h2>The Current Time:
               Date date = new Date ();
               out.println (date);

                                         Error status by tomcat

Error- org.apache.jasper.JasperException: /jsp/Date.jsp (1,1) Unterminated &lt;%@ page tag.

                           Errors occurs in Directives and Standard Actions

Another source of common errors occurs in syntax or mistakes in directives or standard actions.

Example -1: <%@ page lang=”java” %>
Here, the attribute name language not “lang” error occurs in this page directive.

Example – 2: <jsp:include page=”success.jsp” /> Here, The Error occurs when there is no such JSP


       A translation time error occurs while the container translates the JSP code to the JAVA code. A
Request time error occurs while converting the translated java byte code to executable code which is
used to process the request of the browsers. This type of errors also called as Run-Time Errors.


       JSTL tags are customs actions and will generate code during the translation time. Like JSP
standard actions, JSTL actions works with dynamic parameters and attribute values. EL expression
errors occurs only while request the page, this means EL errors occurs only at request time.

                    Integrating Servlets and JSP: The MVC Architecture

If you have a complicated application that may require several substantially different presentations, a
servlet can handle the initial request, partially process the data, set up beans, and then forward the results
to one of a number of different JSP pages, depending on the circumstances. This approach is known as
the Model View Controller (MVC).It consists three distinct but interrelated units.

Model: - This is business logic of application, responsible for performing the actual work conducted by
the application. (e.g: Java Bean)
View:-This is a presentation logic of the application responsible mainly for rendering of the application.
It may have little programming logic.(e.g: JSP/HTML page)
Controller:- This is a Requesting processing Logic of the application, mainly responsible for coupling
both the model and view together.(e.g. servlet)


   In MVC, a controller handles the user request instead of another JSP. The controller is implemented
   as a Servlet. The following steps are executed when the user submits the request.

   1. The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should
       point to the controller servlet).
   2. The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters
       (and optionally also based on session attributes).
   3. The JavaBeans talks to the middle tier or directly to the database to fetch the required data.
   4. The Controller sets the resultant JavaBeans (either same or a new one) in one of the following
       contexts – request, session or application.
   5. The controller then dispatches the request to the next view based on the request URL.
   6. The View uses the resultant JavaBeans from Step 4 to display data.


      CLIENT                                                                            Database


Sharing data between pages, request and users
      The web application consists of more than a single page, and multiple pages often need access to
the same information and server-side resources. When multiple pages process the same request, there
must be a way to pass data from one page to another. For example in an Online shopping application
there must be a way to collect the information received with each request and get access to the complete
when the user is ready.

Passing control and Data between Pages :
       One of the most fundamental features of JSP technology is that it allows separation of request
processing, business logic and presentation known as MVC Model.
Example:-The JSP pages are used for both the controller and view roles, and model is implemented by
either a bean or a JSP page.
1.Dispaly the form for user input(presentation)
2.Validate the input (Request Processing and Business Logic)
3.Display the result of the Validation(presentation).

Explanation:-The input.jsp page displays the input form. The user submits this form to validate.jsp to
validate the input. This page is processes the request using the Bean and passes the control to either
input.jsp page (if the input is valid) or to the inputInvalid.jsp page(if the input is invalid) displays
“Thank you” message.


                                          valida               inputValid.jsp
          input.jsp                       te.jsp


       In the above example, The validate.jsp act as controller, Bean as a Model and the input.jsp,
inputValidate.jsp act as views. This gives the flexibility and maintainability. If the validation rules
changes , a Java programmer can change the Bean without touching any other part of the application. If
the customer wants different look-n-feel a designer can modify the form view without disturbing the
business logic. Using different JSP pages as controller and Views means that more than one page is used
to process a request. To make this happen, you need to be able to do two things.

1. Pass Control from one page to another: As shown in the above diagram, the validate.jsp passes
control to one of the two other pages based on the result of the input validation, It can be accomplished
by using <jsp:forward> action.

                                 <jsp:forward page=”userValid.jsp” />

The <jsp:forward> actions stops processing of one page and starts processing the page specified by the
page attribute called target page.

2. Pass Data from one page to another: JSP provides different scopes for sharing data objects between
pages , request , and users. The scope defines how long the object is available and whether it is available
only to one user or to all application. The following defines the scopes in JSP environment
      page: The page scope is available only within that page(default scope)
      request: The request scope object is available to all the pages processing the same request.
      session: The session scope is available to all request made from the same browser.
      application: This scope is shared by all users of the application.
The <jsp:useBean> action has a scope attribute used to specify the scope of the bean as follows

<jsp:useBean        id=”DataBean”         scope = “ request “      class=”com.feroz.DataBean” />

Sharing Session and Application Data

       The request scope makes data available to multiple pages processing the same request. But in
many cases data must be shared over multiple requests. For instance in a travel agency application, It is
important to remember the dates and destination entered to book the flight so that the customer doesn’t
have to re-enter the information .This type of information , available only to request from the same user,
can be shared through the session scope. Some information is needed by multiple independent of current
users. JSP support access to this type of shared information through the application scope. Information
stored in the application scope by one page can be accessed later by another page, even if the two pages
were requested by different users. Example user logged-in.
<%@ page language="java" %>
<body bgcolor="#FFCCFF">
<form method="post" action="second.jsp">
<table width="40%" border="1">
<caption><b>Sharing data between pages using Session object<b></caption>
   <td>Name:</td><td><input type="text" name="name"></td>
  <td>Password:</td><td><input type="password" name="password"></td>
   <td colspan="2" align="center"><input type="submit" value="submit"></td>


<%@ page language="java" %>
 String name=request.getParameter("name");
 String password = request.getParameter("password");
  <title>Session continues..</title>
 <a href="third.jsp">Click to view the next session..</a>
 <br><br> <br><br>


<%@ page language="java" %>
 String username= (String)session.getAttribute("Name");
 String password= (String)session.getAttribute("Password");
  <title>End of Session..</title>
<body> <CENTER>
  <b> UserName : <%= username %></b>
  <b> Password : <%= password %></b>
 <br><br> <br><br> <br><br> <br><br>

Memory usage consideration
       Every objects created in the application scope and session scope takes up some memory in the
server process. It is easy to calculate that how much memory is occupied by the application scope object
but the session scope needs an extra information to calculate the memory usage, such as number of
concurrent sessions in addition to the size of each object and also to know how long a session last.
The following ways to keep the memory requirements under control when using the session scope
    Place only objects that really need to be unique for each session in the session scope. In the
       shopping cart catalog, each cart refers only the references to the product beans(not copies of the
    set the Time Out period for sessions to a lower value than default, using the method
       setMaxInactiveInterval() in the web.xml file.
    Provide a way to end the session explicitly by calling the method of invalidate() of HttpSession

                         Java Database Connectivity (JDBC)
Accessing the database through an application programming language (JAVA) is called jdbc
connectivity. It sits between your application and the database you want to access. The JDBC is a pure
Java API used to execute SQL statements. It provides a set of classes and interfaces that can be used by
developers to write database applications.

                                             JDBC Architecture

                                             Java Application

                                               JDBC Driver

                                              JDBC Manager

                      Oracle                      MySQL                   SQL
JDBC Works:

      Java application establishes connection with the data source.
      Then Java application loads the corresponding driver for database.
      The JDBC driver connects to the corresponding database and sends Queries and retrieves the
      These results are based on SQL statements which can be returned to Java application.
      Java application uses the retrieved information for further processing.


        Sun has defined four JDBC driver types. Each of these types meets a different application need.

Type 1: JDBC-ODBC Bridge Driver

        The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver.
ODBC is generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use if no
alternative is available.

                                            Java Application

                                               JDBC API

                                             Bridge Driver


                                               Data Base


    The JDBC-ODBC Bridge Driver allows access to almost any database, since the database’s ODBC
drivers are already available.


1. Since the Bridge Driver is not written fully in Java, Hence it is not portable.
2. The performance of this driver is very slow when compared to all drivers.
3. The client requires the ODBC Installation to use this driver.
4. It is not recommended for web application (not good)

Type 2: Native-API Partly-Java Driver

          The Native to API driver converts JDBC commands to DBMS-specific native calls. These
drivers do have an advantage over Type 1 drivers because they interface directly with the database. i.e
This driver converts JDBC calls to database specific call . for example ,Oracle will have oracle native

                                           Java Application

                                               JDBC API

                                          Native API Driver

                                               Native API

                                              Data base


       Type 2 driver typically offer better performance than Type 1 driver as the layer communication are
less than of Type 1 and it uses Native api which is database specific.


1. Native API must be installed in the client system.
2.It is also not written in Java. Hence it is not a portable
3.If we change the database we have to change the native api
4.It is not a Thread Safe.

Type 3: JDBC-Net Pure Java Driver

       The JDBC-Net driver uses in three-tier architecture. This type of driver translates JDBC calls
into a database-independent network protocol that is sent to a middleware server. This server then
translates this DBMS-independent protocol into a DBMS-specific protocol, which is sent to a particular
database. The results are then routed back through the middleware server and sent back to the client.
This type of solution makes it possible to implement a pure Java client. It also makes it possible to swap
databases without affecting the client. This is by far the most flexible JDBC solution.

                                                  Application Space

                                                 Type 3 JDBC Driver

                             SQL Command                               Result Set

                                                 Middle Ware Space

                                                     JDBC DRIVER

                                                                   Proprietary Protocol

                                                      Data Base


1. This driver is server – based driver so there is no need for any vendor database library to be present on
client machines
2. It is fully written in Java and hence portable and it is suitable for internet web application.
3. It can be used for optimize portability, performance and scalability.
4.The net protocol can be designed to make the client JDBC driver very small and fast to load.
5.It can be support for load balancing, connection, query results, logging and auditing features.
6.It is more flexible to allow multiple database using one driver.

Disadvantage : It requires a server to install and maintain .

Type 4: Native-Protocol Pure Java Driver

       The Type 4 drivers are pure Java drivers that communicate directly with the vendor’s database
by converting JDBC commands directly into the database engine’s native protocol. The Type 4 driver
has a very distinct advantage over all the other driver types. It has no additional translation or
middleware layer, which improves performance tremendously.

                                           Java Application

                                              JDBC API

                                        Type 4 JDBC driver

                                              Data base


1.It is completely written in Java to achieve platform independence and eliminate deployment
administration issues and it suitable for web application.
2.Number of translation layers is less. i.e Type 4 JDBC drivers don’t have to translate database request
to ODBC or native connectivity interface.
3.You don’t need to install special software on the client or server.

Disadvantage: The user needs a different driver for each database.

                                  Exploring the java.sql Package

The java.sql package provides the API for accessing and processing data in a data source.

      The DriverManager class
      The Driver interface
      The Connection interface
      The Statement interface
      The ResultSet interface
      The PreparedStatement interface
      The ResultSetMetaData interface

1. The DriverManager class: The DriverManager class provides static methods for managing JDBC
drivers. It uses the static method forName() of Class to locate and load the drivers named in the system
variables jdbc.drivers. Each JDBC driver must be registered with the DriverManager.
                         Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”)

This code snippet loads the driver dynamically specified by the string parameter.

public static synchronized Connection getConnection(String url,String user,String pwd) : This
method returns the connection object of the database in order to access to the datasource.

2. Driver interface: The Driver interface provides methods for establishing the connections with
specific database. such methods use a URL type string as parameter to locate and access database. The
Driver interface is implemented by every JDBC driver class. The driver class itself is loaded and
registered with the DriverManager, and the DriverManager can manage multiple drivers for any given
connection request.
                      JDBC URL Syntax:           jdbc : <subprotocol>:<subname>

Here, <subprotocol> defines the type of driver and <subname> provides the network encoded database
being access.
                                     e.g.: jdbc: oracle: products

3. The Connection interface: This interface is used to establish a connections to the database. An
instance of the Connection interface is obtained from the getConnection method of the DriverManager
                       Connection conn = DriverManager.getConnection(URL);

public void close() : This method is used to close the database.
public boolean isClosed() : This method is used to test whether the connection is closed or not.
public abstract Statement createStatement() : This method returns the statement object.
                               Statement stm = conn.createStatement();

public abstract CallableStatement prepareCall(String sql) : It will return the instance of the Callable
Statement which can be handle the stored procedures.
public abstract PreparedStatement         prepareStatement(String sql) : This returns the          prepared
Statement object configured with the sql String passed.
public abstract void commit() : This method makes all the changes made committed from the
public abstract void rollback() : This method cancel all the changes made to the database from the

Note : All the above methods throws SQLException.

4. Statement interface: This interface is used to send the SQL queries to the database and retrieve a set
of data. The most important methods of this interface are executeQuery and executeUpdate.
executeQuery : The executeQuery method executes an SQL statement that returns a single ResultSet
object. Its signature is as follows:
              public abstract ResultSet executeQuery(String sql) throws SQLException

executeUpdate : The executeUpdate method executes an insert, update, and delete SQL statement. The
method returns the number of records affected by the SQL statement execution.

                              public abstract int executeUpdate(String sql)

Example :

                  Connection conn =DriverManager.getConnection(database url);
                  Statement stm = conn.createStatement();
                  ResultSet result = stm.executeQuery(“SELECT name from employee”);

5. Prepared Statement interface: It extends Statement interface. It is used to pass parameters into an
SQL Statements. The following methods are available in this interface.

public abstract void setInt( int index, int i ) throws SQLException
public abstract void setFloat( int index, float f ) throws SQLException
public abstract void setDouble( int index, double d ) throws SQLException
public abstract void setString( int index, String str ) throws SQLException
public abstract void setLong( int index, long l ) throws SQLException
public abstract void setByte( int index, byte b ) throws SQLException.


PreparedStatement ps = conn.prepareStatement(“UPDATE catalog SET price=? WHERE

6. The CallableStatement interface : This interface extends PreparedStatement interface and can be
used to execute stored SQL procedures.

public abstract void getInt( int index ) throws SQLException
public abstract void getFloat( int index ) throws SQLException
public abstract void getDouble( int index) throws SQLException
public abstract void getString( int index) throws SQLException
public abstract void getLong( int index ) throws SQLException
public abstract void getByte( int index ) throws SQLException.

7. ResultSet interface: This interface contains the methods used to retrieve the data from upon
execution of SQL statements.
public abstract boolean next() : It reads the current row position of data. It returns false if the row
position is empty.
public abstract void getString( int index) :It returns the String value stored in column with index
public boolean isFirst() throws SQLException : This method indicates whether the cursor points to
the first record in the ResultSet.
public boolean isLast() throws SQLException : The isLast method indicates whether the cursor points
to the last record in the ResultSet.

ResultSet result = stm.executeQuery(“SELECT name from employee”);
    System.out.println(“Name : ” + result.getString(“Name”));

8. The ResultSetMetaData Interface: The ResultSetMetaData interface represents the meta data of a
Result Set object.

public int getColumnCount() throws SQLException : The getColumnCount method returns the
number of columns in the ResultSet whose meta data is represented by the ResultSetMetaData object.
public String getColumnName(int columnIndex) throws SQLException : The getColumnName
method returns the column name as the specified column index. The first column is indicated by index
number 1.

                          The executeUpdate and executeQuery Methods

  The executeUpdate method executes an SQL INSERT, UPDATE, or DELETE statement and
  also data definition language (DDL) statements to create, drop, and alter tables. This method
  returns the row count for INSERT, UPDATE, or DELETES statements or returns 0 for SQL
  statements that return nothing.
  The executeQuery method executes an SQL SELECT statement that returns data. This method
  returns a single ResultSet object that contains the data produced by the given query. This method
  never returns a null.

JDBC Programming / Connection to Database using JDBC: Database programming using JDBC
involves the following steps
    Loading the JDBC Driver for Database using JNDI
    Getting the connection to the Data Source.
    Create and Executing SQL Queries.
    Process the results.
    Close the Connection

   1. Loading the JDBC Driver for Database using JNDI : If you want to access a particular
       database, you need to get the JDBC driver for that database. JDBC Drivers are available for most
       popular databases such as Oracle, Sybase, DB2, Microsoft SQL Server, MySQL. You can load
       the JDBC Driver by using the static method forName() of Class.
                                   Class.forName (“”);

          Here, the driver name is the different types of drivers for different Database.

                    Driver Name                                                RDBMS
oracle.jdbc.driver.OracleDriver                          ORACLE
com.mysql.jdbc.Driver                                    MySQL             SQL Server
sun.jdbc.odbc.JdbcOdbcDriver                             MS-Access

2. Getting /Creating a Connection: After Loading the Driver successfully, we need to create a
Database     Connection using a static method getConnection(url) of             DriverManager class. The
following code shows how you obtain a Connection object to a MySQL database named FerozOne in a
server called local host. You also pass the user "admin" and the password "rits" to the getConnection
Connection conn = DriverManager.getConnection ("jdbc:mysql///localhost:3036/FerozOne",
"admin", "rits");
                                    Or for MS-Access
Connection con = DriverManager.getConnection("jdbc:odbc:FerozOne");

3.Creating and Executing SQL Queries: After you have a Connection object from the
DriverManage.getConnection method, you are ready to pass a SQL statement. To do this, you need to
create another JDBC object called Statement. You can do this using the createStatement() method of
the Connection interface. Therefore, to create a Statement object from an open Connection object.

                              Statement stm = connection.createStatement();

After creating the statement , the methods in the Statement class interface to manipulate your data or
data structure using executeUpdate and executeQuery. For example, to create a table named Royal
with two fields.
String sql = "CREATE TABLE Royal " + "(Name VARCHAR (32), Branch VARCHAR(32)";

And, to insert a record in the Royal table.

String sql = "INSERT INTO Royal VALUES ('feroz', 'CSIT')";

4. Processing the Result: To process the result we use an interface called ResultSet which consists
methods used to get the data from the database returned from the Statement object. It uses a method
called next() to point the cursor position of each row in a table and using the another method getXXX()
to get the data from the field of tables.

String sql = "SELECT Name, Branch FROM Royal";
ResultSet resultSet = statement.executeQuery(sql);
while (
   System.out.println (resultSet.getString (1) + ":" +resultSet.getString ("Branch"));
Here, the index 1 points to the first column in a table Royal

5. Closing the Database Connection : After getting or processing the database we have to close the
connection using the close method.


A JDBC Program

import java.sql.*;
import javax.swing.JOptionPane;
public class DatabaseAccess
        public static void main(String[] args)
          String name="", branch="";
               //Loading the Driver-----step---1
              Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch(Exception e){}

            //Creating the Connection ---step----2
              Connection con = DriverManager.getConnection ("jdbc:odbc:FerozOne");
            //Creating the Statement object to execute the SQL Queries –step--3
              Statement statement = con.createStatement();
              String sql="SELECT Name,Branch FROM Royal”;
             //Excuting the QUERY—step ---3
              ResultSet resultset = statement.executeQuery(sql);
             while( /Process the Result—step--4
           } catch(SQLException e){System.out.println(e.getMessage());}
          System.out.println(Name : " +name+"\nBranch : "+branch);

Accessing/displaying the Data from the Data Base using JSP - JDBC

<%@ page import="java.sql.*" %>
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
}catch(Exception e){}
      <title>Accessing the data from Database Table </title>
   <body bgcolor="#99cccc">
      <center><h1>Accessing the Data From Database Table</h1>
          ResultSet resultset=null;
       Connection connection = DriverManager.getConnection("jdbc:odbc:FerozOne");
       Statement statement = connection.createStatement() ;
        resultset = statement.executeQuery("select Rollnumber,Name, Branch from Royal") ;
<table border="1" bgcolor="#e6dfc4" width="80%">
 <% while({ %>
                    <%= resultset.getString(1)%>
                  <%= resultset.getString(2)%>
                 <%= resultset.getString(3)%>
      <% }
      catch(Exception e){}

A JSP program that insert a new Employee data into the database using prepareStatement
                                  Program: newEmployee.html

<title>Employee Details</title>
<script language="javascript">
 function validation(form_obj)
      var na= document.getElementById("ename").value;
      var desg= document.getElementById("designation").value;
      var dep= document.getElementById("department").value;
            alert("Please fill up remaining information!!");
            return false;
          alert("Please fill up remaining information!!");
          return false;
          alert("Please fill up remaining information!!");
          return false;
  return true;
<body bgcolor="#99CC66">
 <form name="entry" action="EmployeeForm.jsp" method="post" onSubmit="return validation(this)">
 <input type="hidden" value="list" name="action">
 <table border="5" width="50%" bordercolor="black">
               <td colspan="2" align="center"> <h2>Employee Entry Form</h2> </td>
                <td>Employe Name:</td>
                <td><input type="text" name="ename" size="50">
                <td><input type="text" name="designation" size="50">
                <td><input type="text" name="department" size="50">
                 <td colspan="2" align="center"> <input type="submit" value="submit"> </td>

                                   program: EmployeeForm.jsp

<%@page import="java.sql.*"%>
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet res=null;
      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root", "root");
      out.write("Coonected to the database");
            String ename = request.getParameter("ename");
            String designation = request.getParameter("designation");
            String dept = request.getParameter("department");
            String query = "insert into employee_table(Name,Designation,Department)values(?,?,?)";
            res=pstmt.executeQuery("select * from employee_table");
     catch (SQLException e) {
         System.out.println("Error occurred " + e);
<body bgcolor="#99CC66"><center><h1><u>RITS Employee Data<u></h1>
<table border="1" cellspacing="1" cellspacing="2" width="50%" border="2">
  <td><b>EMPLOYEE NAME </b></td>
  <td><b>DESIGNATION </b></td>
 int num=1;

}catch(Exception e){}

                                  Model 2 Architecture – MVC

MVC stands for Model View Controller. The Model 2 JSP architecture is actually MVC applied to web

                                     <Controller>                 V
                                       Servlet                    A

    Browser                                                       A
                                                                  |                       Source
                                           <View>                 E
                                            JSP                   L

In Model 2, a controller handles the user request instead of another JSP. The controller is implemented
as a Servlet. The following steps are executed when the user submits the request.

   7. The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should
       point to the controller servlet).
   8. The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters
       (and optionally also based on session attributes).
   9. The JavaBeans talks to the middle tier or directly to the database to fetch the required data.
   10. The Controller sets the resultant JavaBeans (either same or a new one) in one of the following
       contexts – request, session or application.
   11. The controller then dispatches the request to the next view based on the request URL.
   12. The View uses the resultant JavaBeans from Step 4 to display data.

Note That there is no presentation logic in the JSP. The sole function of the JSP in Model 2 architecture
is to display the data from the JavaBeans set in the request, session or application scopes.

What wrong with MVC

       If you follow MVC architecture you can have as many as controllers but it is not recommended
that you should use only one controller,so that the duplication of code can be eliminated. But a single
controller servlet for a complex web application may give poor performance and sometimes fails to meet
the requirements. so, we follow another Framework called STRUTS.


                                ActionServlet                               Action


                                                                                                Data Base

       In Struts, there is only one controller servlet for the entire web application. This controller servlet
is called ActionServlet and resides in the package org.apache.struts.action. It intercepts every client
request and populates an ActionForm from the HTTP request parameters. ActionForm is a normal
JavaBeans class. The ActionServlet then instantiates a Handler. The Handler class name is obtained
from an XML file based on the URL path information. This XML file is referred to as Struts
configuration file and by default named as struts-config.xml. The Handler is called Action in the Struts
terminology. This class is created by extending the Action class in org.apache.struts.action package. The
Action class is abstract and defines a single method called execute().


    The ActionServlet receives a client HTTP request and delegates the request to the
       Handler(Action) by invoking the process() method, which is configured in the struts-config.xml
    The Action or RequestHandler instantiates the Bean in order to invoke the business logic.
    The Bean class is called a Model which is used to retrieve or save the data based on the request
       from the Action.

    After setting – getting the data from the Model it set in the scope (Session, application,
       request). And get back to the Request Handler (Action) class.
    The Action class get the view and response back to the ActionServlet.
    The Action Servlet controller maps the URL of the view in the xml file and dispatches the view
       (a JSP file) back to the client as a HTTP response.

Asynchronous JavaScript and XML (AJAX)
       Ajax is nothing more than an approach to create Rich Internet web application which is more
interactive. This approach involves transmitting only a small amount of information to and from the
server in order to give the user the most responsive experience possible.
       Instead of the traditional web application model where the browser itself is responsible for
initiating requests to, and processing requests from, the web server, the Ajax model provides an
intermediate layer— called as Ajax engine—to handle this communication. An Ajax engine is really just
a JavaScript object or function that is called whenever information needs to be requested from the
server. Instead of the traditional model of providing a link to another resource (such as another web
page), each link makes a call to the Ajax engine, which schedules and executes the request. The request
is done asynchronously, meaning that code execution doesn’t wait for a response before continuing.
       The server—which traditionally would serve up HTML, images, CSS, or JavaScript—is
configured to return data that the Ajax engine can use. This data can be plain text, XML, or any other
data format that you may need. The only requirement is that the Ajax engine can understand and
interpret the data When the Ajax engine receives the server response, it goes into action, often parsing
the data and making several changes to the user interface based on the information it was provided.
Because this process involves transferring less information than the traditional web application model,
user interface updates are faster, and the user is able to do his or her work more quickly. Figure
displaying the difference between the traditional and Ajax web application models.
                                     Traditional Web Application Model

       Web browser
                          HTML,CSS, JavaScript                      Data

                                                                                         Data Base

                              HTTP Request                    Query/Data Request

                                                             Web Server


                                        AJAX Web Application Model

                    Web browser
                                                    Data                           Data
                     HTML & CSS
       User                           AJAX
       Interface                      Engine                                                 Data Base
                    Java Scipt Call
                                                  Http request                 Query/
                                                                              Data request

                                                                 Web Server

Technologies behind Ajax: The following are the technologies as parts of an Ajax solution.

❑ HTML/XHTML: Primary content representation languages
❑ CSS: Provides stylistic formatting to XHTML
❑ DOM: Dynamic updating of a loaded page
❑ XML: Data exchange format
❑ XSLT: Transforms XML into XHTML (styled by CSS)
❑ XMLHttp: Primary communication broker
❑ JavaScript: Scripting language used to program an Ajax engine

       In reality, all these technologies are available to be used in Ajax solutions, but only three are
required: HTML/XHTML, DOM, and JavaScript. XHTML is obviously necessary for the displaying of
information, while the DOM is necessary to change portions of an XHTML page without reloading it.
The last part, JavaScript, is necessary to initiate the client-server communication and manipulate the
DOM to update the web page.

Ajax Principles: The following are the key principles of good Ajax applications.

      Minimal traffic: Ajax applications should send and receive as little information as possible to
       and from the server. In short, Ajax can minimize the amount of traffic between the client and the
       server. Making sure that your Ajax application doesn’t send and receive unnecessary information
       adds to its robustness.

     No distractions: Avoid unnecessary and distracting page elements such as looping animations
      and blinking page sections. Such gimmicks distract the user from what he or she is trying to
     Avoid entire page downloads: All server communication after the initial page download should
      be managed by the Ajax engine. Don’t ruin the user experience by downloading small amounts
      of data in one place but reloading the entire page in others.
     User first: Design the Ajax application with the users in mind before anything else.
     No surprises: Ajax applications typically introduce different user interaction models than
      traditional web applications. As opposed to the web standard of click-and-wait, some Ajax
      applications use other user interface paradigms such as drag-and-drop or double-clicking. No
      matter what user interaction model you choose, be consistent so that the user knows what to do


To top