Vous êtes sur la page 1sur 37

ActiveNET

JSP chapter
Digital Book www.activenetindia.com 1

7 -- /, 7 -- /, 7 -- /, 7 -- /,
...,...1 ., ...,...1 ., ...,...1 ., ...,...1 .,

...... .. ... ...... .. ... ...... .. ... ...... .. ...
]SP ]SP ]SP ]SP A dqaamic h1Ml paqe A dqaamic h1Ml paqe A dqaamic h1Ml paqe A dqaamic h1Ml paqe
DHTmL -{{r {- DvuAmic HTmL
DHTmL is fhe orf of moking HTML dynomic by combining HTML, CSS ond JovoScripf
fechnoIogies
)5P mokes HTmL ovuAmic by combining HTML ond server side Jovo execufion fhof
heIps fo produce dofo coIIecfed from vorious dofo sources (XML, D8, FiIe, Spreod Sheef,
Direcfory Service efc)
TabIe ot Conrenr
Evolution of JSP
Introduction to JSP
JSP Architecture
JSP Lifecycle
Comparing JSP with Servlets
Scripting elements
Directive Elements
JSP Standard Action elements
Implicit objects
Scope variables
Separating model layer from JSP document using JSP Bean
JSP Model1 Architecture
JSP Model2 architecture
Separating business logic, model and dynamic presentation from JSP
documents using TagHandlers
JSP Custom Tags & TagHandlers
JSP Tag Ext API
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 2
Implementation on Empty, Element-Only and Text-Only elements
JSP Standard Tag Libraries(JSTL)
JSP 2.0 Topics


Difference between Web Component and Web Application Difference between Web Component and Web Application Difference between Web Component and Web Application Difference between Web Component and Web Application
Web Application means .war file
Web Component means Servlet, JSP, Filter, Listener

Why JSP Why JSP Why JSP Why JSP? ? ? ? since Servlets are already there in the market? since Servlets are already there in the market? since Servlets are already there in the market? since Servlets are already there in the market?
HTML code embedded in Servlet is cumbersome / awkward
Separation of duties

JSP means JSP means JSP means JSP means
ML + Java => JSP ML + Java => JSP ML + Java => JSP ML + Java => JSP
Markup language tags and java statements are combined into one single web
document. (SGML+Java)

Advantages of using JSP Advantages of using JSP Advantages of using JSP Advantages of using JSP
Powerful - they are servlets
Efficient - they are compiled into bytecode
Portable - they are standardized, they work in multiple containers
Convenient - they use the JavaBeans component architecture
Flexible - can use Custom Tags
Easy - Uses HTML/XML and Java

Disa Disa Disa Disadvantages of using JSP dvantages of using JSP dvantages of using JSP dvantages of using JSP
Separating business logic from presentation logic is easier said than done
Without a framework, many of the problems of web development still exist
Application flow can get lost in the presentation layer
Business logic in the presentation layer
Java in the HTML is still difficult for non-programmers
Learning JSPs can feel like a different language, more to learn
Debugging (without a good IDE) can be a little more difficult

However, if done correctly, all the problems with JSPs can be taken care of, and they
are preferred to using servlets for presentation.

History of JSP History of JSP History of JSP History of JSP
Servlet spec 2.1 was delivered in January 1999
2.2 was delivered in December 1999
JSP 1.0 was delivered in June 1999
JSP 1.1 was delivered in December 1999
JSP 1.2 was delivered in 2001.
JSP 2.0, a major version upgrade, went final in November 2003
Servlet 2.1/ JSP 1.0 (Sun Servlet RI)
Servlet 2.2/ JSP 1.1 (Tomcat 3.x)
Servlet 2.3/ JSP 1.2 (Tomcat 4.x)
Servlet 2.4/ JSP 2.0 (Tomcat 5.x)
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 3
The basic "Hello World" servlet
import import import import javax.servlet.*;
import import import import javax.servlet.http.*;

public public public public class class class class HelloServlet2 extends extends extends extends HttpServlet {
protected protected protected protected void doGet doGet doGet doGet(HttpServletRequest request, HttpServletResponse
response)
throws throws throws throws ServletException, java.io.IOException {
response.setContentType setContentType setContentType setContentType("text/html");
java.io.PrintWriter out = response.getWriter getWriter getWriter getWriter();

out.println println println println("<html>");
out.println println println println("<head>");
out.println println println println("<title>Hello Servlet</title>");
out.println println println println("</head>");
out.println println println println("<body>");
out.println println println println("<h1>Hello World!</h1>");
out.println println println println("The time is <i>" + new new new new Date Date Date Date() + "</i>" );
out.println println println println("</body>");
out.println println println println("</html>");
out.close close close close();
}
}

<html>
<head>
<title>Hello JSP</title>
</head>
<body>
<h1>Hello World</h1>
The time is <%= new java.util.Date() %>
</body>
</html>

Basically, treat a JSP like an HTML file. You can place it anywhere inside the
document root of your webapp.
Do not copy your JSPs into the WEB-INF directory if you want to access them
directly, since they cannot be accessed from there via their name. When you are
using a JSP with a Servlet, you can do this. This is an excellent way to implement
security on your pages. More on this later
Example:
Copy Hello2.jsp to "tomcat home"/webapps/ROOT and Invoke
http://localhost:8080/Hello2.jsp
When using a war file, just include the JSP in the directory where you want to access
it, make the war file, and deploy. You should be able to see the changes when the
servlet engine reloads the war file
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 4
So how does a JSP actually work?
It is turned into a special kind of servlet. The code is generated by a JSP compiler,
which generates Java code out of it. This is the Java code that will be run while you
test your JSPs. Sometimes, you'll need to take a look at the code to understand what
is happening
Tomcat, for example, places the intermediate .java files in
"tomcat_root"/work/Catalina/localhost/"webapp name".
Tomcat retains the .java source by default. This will vary by servlet container
implementation, some require you to turn a debug option on to save source
Tomcat, by default, places the JSP code in the org.apache.jsp package.
Here is the code that is generated by Tomcat for the example above:
Though it is not that important to deeply involve in understanding the below code, Though it is not that important to deeply involve in understanding the below code, Though it is not that important to deeply involve in understanding the below code, Though it is not that important to deeply involve in understanding the below code,
but it is only for a knowledge sake. Dont gran but it is only for a knowledge sake. Dont gran but it is only for a knowledge sake. Dont gran but it is only for a knowledge sake. Dont grant more time on this t more time on this t more time on this t more time on this
import javax.servlet.jsp.*;

public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {

private static java.util.Vector _jspx_dependants;

public java.util.List getDependants() {
return _jspx_dependants;
}

public void _jspService(HttpServletRequest request, HttpServletResponse
response)
throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;


try {
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 5
out = pageContext.getOut();
_jspx_out = out;

out.write("\n");
out.write("<html>\n ");
out.write("<head>\n ");
out.write("<title>Hello JSP");
out.write("</title>\n ");
out.write("</head>\n ");
out.write("<body>\n ");
out.write("<h1>Hello World");
out.write("</h1>\n The time is ");
out.write(String.valueOf( new java.util.Date() ));
out.write("\n ");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (pageContext != null) pageContext.handlePageException(t);
}
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
}
}
}
Based on what you already know about Servlets, what do you think of the time
writing this as a JSP has saved you? We'll look at some more detail on other
convenient things done for you by the JSP compiler later. If you study this code
above, you can probably figure most of them out without the specification!
Servlets
Precompiled
Class files placed in doc root/WEB-INF/classes
JSPs
Compiled either at startup or at first invocation by servlet engine
JSP compiler - converts JSP to Java code
Java compiler - compiles Java code to byte code
Uses the same classpath as the webapp (so put your bean and utility classes
in doc root/WEB-INF/classes
Origin of JSP Origin of JSP Origin of JSP Origin of JSP
The past five years have seen tremendous change in server-side Web page
generation technology. As the need for dynamic Web sites emerged, early protocols
such as CGI proved to be too limiting, and too difficult to provide the level of
performance required by dynamic sites. The market quickly recognized a need to
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 6
build a better system which was more accessible to people building the sites, as well
as the ability to provide for server-side performance enhancements. Systems such as
Allaire's ColdFusion and Microsoft's Active Server Pages quickly gained popularity in
the Web development community. In version 2 of ATGs software, we introduced
JHTML and its page compilation technology as a way to build server-side applications
using Java. This version of the software also introduced component-based Web
applications with its Dynamo Foundation Classes. Sun then created the Servlet
specification, providing a standard for server-side Java applications. Soon after, ATG
released version 3, which added the ability to take JHTML files and compile them into
Servlets at runtime. Sun licensed this technology from ATG to create the JavaServer
Pages specification.

Over time, both the JHTML and JSP technologies evolved independently of one
another. ATG (with JHTML) began to prove itself as a mature environment for
creating high-performance Web applications, which strongly emphasized the
separation of presentation and application logic. ATG took advantage of Suns
JavaBeans specification to simplify the process of building applications using the
"droplet concept of embedding references to executable components. Also, version
3 of our software gave JHTML the ability to bind JavaBeans properties to HTML form
elements, which allows powerful Web-based interfaces to be created without a steep
learning curve, which is still not currently possible with JSP. However, with the help
of Sun's marketing efforts, JSP became the leading Java-based Web programming
language. Unfortunately, this created a conflict: J2EE was released, which provided
specifications and blueprints on how to build multi-tier applications with Java. JSP is
one of the major specifications of J2EE. Version 5 of our software introduced ATG's
J2EE application container, but at that time, many of the ATG applications still used
the mature JHTML model. The following diagram (Figure 1) shows how the Dynamo
Model is parallel to the J2EE Model:


Fortunately, the JSP 1.1 specification included the concept of a "tag library." Tag
libraries are a mechanism by which a J2EE application can provide custom tags that
fall outside of the JSP specification. In essence, they allow the developer to put
custom Java code outside the JSP page, much like ATG's JHTML and Droplet
technique of separating presentation and application logic. This enhancement
allowed JSP to catch up to JHTML in terms of power of expression. With market
forces driving J2EE into more enterprises, ATG applications required the ability to
work with JSP. In order for ATG to move its applications to a JSP model, and to
provide a quick way for JHTML authors to bring their applications and experience to
J2EE while allowing ATG to be used by JSP authors, ATG engineers reformulated
JHTML as a JSP Tag library. This has also given the benefit of greatly simplifying the
process of porting ATG to work on other, non-ATG J2EE application servers. This
technology, known as the Dynamo Application Framework, is illustrated in Figure 2
below. As of version 5.6.1, the demos that ship with ATG (Quincy Funds, Pioneer
Cycling, and Motorprise) all run as JSP-based applications by default.
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 7

Evolution of JSP Evolution of JSP Evolution of JSP Evolution of JSP
HTML produces Static Web-Pages, but today it is necessary for most Web Sites to
have dynamic Content. To generate the content dynamically we need something that
can allow us to specify Business Logic and that can generate Response to the
Request. The Data can then be formatted using HTML.

A Dynamic Web-Page Consists of HTML Code as well as Programming Language
Code. Instead of Serving the Page as it is to the Clients, a Server Processes the
Programming language code, replaces the code with the Data generated by the code,
and then sends the page to the client. This Methodology of Embedding the
Programming Language Code with in the HTML Document is called the Server-side
include & the programming Language with in the Html is Called as Scripting
Language.

This is the Situation that leads to the Invention of a Html Document that is given
chance of embedding the Java Code for providing the Dynamic Nature to that
Document that which was later named and popularized as JavaServerPages JavaServerPages JavaServerPages JavaServerPages (JSP). (JSP). (JSP). (JSP).

Introduction to JSP Introduction to JSP Introduction to JSP Introduction to JSP
A JSP Page is a web Page that contains Java Code along with the HTML tags. Like
any other Web Page, a JSP Page has a Unique URL, which is used by the Clients to
access the Page. When accessed by the Client the Java code with in the page is
executed on the Server Side, producing Textual data. This data which is surrounded
by HTML tags is sent as a Normal HTML page to the Client. Since the Java code
embedded in the JSP Page is processed on the Server Side, the client has no
Knowledge of the code. The code is replaced by the HTML Generated by the Java
code before the code is sent to the client.

How JSP works How JSP works How JSP works How JSP works? ?? ?
When When When When first time client requests first time client requests first time client requests first time client requests











JSP File JSP File JSP File JSP File Translate Translate Translate Translate
to a to a to a to a
Servlet Servlet Servlet Servlet
Compile Compile Compile Compile
Servlet Servlet Servlet Servlet
Run Run Run Run
Servlet Servlet Servlet Servlet
Returns Returns Returns Returns
HTML HTML HTML HTML
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 8
JSP subsequent request JSP subsequent request JSP subsequent request JSP subsequent request










It is important to understand how JSP works at runtime. A JSP is converted to
Servlet at runtime. The JSP compile process only happens the first time the JSP is
called. The JSP is translated, compiled and then produce HTML O/P. A JSP at runtime
is a specialized HttpServlet. The JSP engine generates a Servlet with jspInit(),
_jspService() and a jspDestroy() operations.The compiled Servlet is saved as a .class
file on the server. When new instance of such a Servlet is created, jspInit() method
executes that followed by _jspService() or every client request and executes
jspDestroy() when web container/web server is shutdown.

JSP container also maintains a process that checks when client requests for the JSP
document, the saved/modified time of the JSP document is compared with the last
compiled time of the JSP. If any variations are found in the timestamp the JSP
container assumes that the source code of the JSP document is modified and then
attempts to recompile the JSP document into Servlet program again.




























Run Servlet Run Servlet Run Servlet Run Servlet
Returns Returns Returns Returns
HTML HTML HTML HTML
1. Checks Well-formed or not
2. Checks Valid or not
3. Translates into Servlet
4. Compiles Servlet class
5. Configures Servlet into
Servlet container
6. and then finally executes JSP
as a Servlet
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 9
Phases in JSP Lifecycle Phases in JSP Lifecycle Phases in JSP Lifecycle Phases in JSP Lifecycle















From the knowledge gained from previous topic we understood several phases
involved in running JSP document as a Servlet program. They are:

As soon as JSP document is requested by the client first (mostly developer requests
are initial requests to JSP document to test whether it is running properly or not):
JSP container employs an XML parser kind of tool to verify whether JSP
document is well-formed document or not (attribute values must be quoted,
elements must be properly nested, for each start element one corresponding
end element/atleast self closing tag must be used).
If above validation is successful, it then checks the syntaxes of the JSP
document (scripting, directive, standard action and user defined elements)
with their corresponding namespace and tlds, if found correct then goes to
next step, otherwise JSP translation error JSP translation error JSP translation error JSP translation error will be experienced.
If any errors are found in the Java syntaxes that cause Java compilation Java compilation Java compilation Java compilation
errors errors errors errors. .. .
o Hence how many error types we found in JSP
JSP translation error if JSP syntaxes gone wrong
Java compilation error if java syntaxes used in the JSP
document are written wrong
Once the Servlet is compiled it is then configured in the Servlet container that
executes JSP compiled Servlet as Servlet
The last phase is Servlet execution

JSP Lifecycle Functions JSP Lifecycle Functions JSP Lifecycle Functions JSP Lifecycle Functions













Validation Validation Validation Validation
Translation Translation Translation Translation
Compilation Compilation Compilation Compilation
Configuration Configuration Configuration Configuration
Execution Execution Execution Execution
jspInit() jspInit() jspInit() jspInit()
_ __ _jsp jsp jsp jspService Service Service Service() () () ()
jspDestroy() jspDestroy() jspDestroy() jspDestroy()

ActiveNET

JSP chapter
Digital Book www.activenetindia.com 10
Comparing JSP with Servlets Comparing JSP with Servlets Comparing JSP with Servlets Comparing JSP with Servlets
Well! If JSP can do everything that Servlet can do? Then what is the difference
between them?
As said above Servlets are the Server extensions that provide extra functionality to
the main server. This includes implementation of specialized services such as:
Authentication
Authorization
Validating client request with database
Transaction Management
Controller component that controls the Business Logic Business Logic Business Logic Business Logic developed by Java
programmers with strong OOP skills

Java Server Pages are Web pages. They are Similar to HTML Pages at design time.
Any Web page designer who has some knowledge of JSP Tags and the basics of Java
can write a JSP Page.

For example take a User-Authentication Example that Accepts the Login and
Password Information. The Code that generates the HTML Form, Success and Error
Messages etc should be in the JSP Page. While the Code that Access the Database
validates the Password and Authenticates the User should be written in the Servlet.
The Final words are
JSP Pages are meant for Visual Representation
Business Logic is deferred to Servlets.

Scripting Elements Scripting Elements Scripting Elements Scripting Elements
There are 5 types of Scripting Elements. They are as Follows
1) 1) 1) 1) HTML comment HTML comment HTML comment HTML comment
<!-- -->
Only formatting instructions (<B><I>) and formatting text (any text content
you write in a HTML document) should be placed in this tag, but not java
statement embedded in scripting elements
If JSP scripting elements are embedded in this comment JSP container will
check the syntax of the Java statements also and informs the syntactical
mistakes to developer
In addition to all the above content placed in this element will be assumed as
HTML content and places as it is in out.println() statement and redirected to
the browser, browser ignores this text during HTML document parsing.
<!--
- Author(s):
- Date:
- Copyright Notice:
-->
2) 2) 2) 2) JSP Comment JSP Comment JSP Comment JSP Comment
<%-- --%>
Only java statements embedded in scripting elements must be enclosed in
this tag but not formatting instructions and formatting text.
Java statements embedded in this tag are ignored by JSP container during
page translation so that content wont be placed in out.println() statement,
hence the content wont come out on to the browser.
There is nothing special placing HTML content in this tag
<%--
- Author(s):
- Date:
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 11
- Copyright Notice:
- @(#)
- Description:
--%>
3) Declaration element 3) Declaration element 3) Declaration element 3) Declaration element
<%!datatype identifier1, iden2;%>
<%!int i,j; String str;%>
Class / class-instance variables are declared in this tag
Similar identifier/variable should be separated with comma and dissimilar
variables should be separated with semi-colon;
There is no limit to use this element in the document
4) Expression element 4) Expression element 4) Expression element 4) Expression element
<%=expression()|identifier|literal%>
Using this element we can display expression evaluated results, identifier values and
literals directly on STDOUT/browser
Ex:
<%=new Date()%>
<%=i%>
<%=10%> <%="abc"%>
5) Scriptlet 5) Scriptlet 5) Scriptlet 5) Scriptlet
<%
---
---
%>
This element is used to execute multiple lines of java statements including try/catch
blocks, statements, conditions, loops var declaration and initialization etc. In simple
words we can say that whatever we want to write in the service method of page
compiled Servlet program in this element.
Directive Elements Directive Elements Directive Elements Directive Elements
There are 3 Directive Elements. They are as follows
1) Include directive 1) Include directive 1) Include directive 1) Include directive
<%@ include file="url"/>
Using this element we can embed HTML, JSP and Servlet evaluated results in the
source JSP document.
2) Page directive 2) Page directive 2) Page directive 2) Page directive
<%@ page import="java.sql.*, java.util.*"%>
Using this element we can import any java or other packages into our JSP
Document
<%@ page page_directive_attr_list %>
page_directive_attr_list ::= { language="java"}
{ extends="className" } - JSP base class
{ import="importList" }
-java.lang.*, javax.servlet.*, javax.servlet.jsp.* and javax.servlet.http.*
{ session="true|false" }
- whether the page participates in a session
{ buffer="none| 8kb |sizekb" }
{ autoFlush="true|false" }
-illegal to make buffer = none when autoflush is false
{ isThreadSafe="true|false" }
{ info="info_text" }
{ errorPage="error_url" }
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 12
{ isErrorPage="true|false" }
{ contentType="ctinfo" } - "text/html"
{ pageEncoding="peinfo" } - "ISO-8859-1"

3) Taglib directive 3) Taglib directive 3) Taglib directive 3) Taglib directive
<%@ taglib uri="" prefix=""%>
This element is used in custom and standard tag libraries to import the tags Used.

JSP Standard Action elements JSP Standard Action elements JSP Standard Action elements JSP Standard Action elements
There are 8 JSP Standard Action Elements available. They are as follows
1) <jsp:forward page="url" scope=""/> 1) <jsp:forward page="url" scope=""/> 1) <jsp:forward page="url" scope=""/> 1) <jsp:forward page="url" scope=""/>
Functionality same as RequestDispatcher.forward(req, resp);

2) <jsp:include page="url" scope=""/> 2) <jsp:include page="url" scope=""/> 2) <jsp:include page="url" scope=""/> 2) <jsp:include page="url" scope=""/>
Functionality same as RequestDispatcher.include(req, resp);
Difference between <%@include> and <jsp:include>: Difference between <%@include> and <jsp:include>: Difference between <%@include> and <jsp:include>: Difference between <%@include> and <jsp:include>:
<%@ include%> documents which are requested to be composed are bound
to current JSP document @ page compilation, execution is faster but if any
changes made to composed document would result recompile the source JSP
document again
<jsp:include/> documents requested to be bound are bound to source JSP
document @ runtime, execution time will be little bit increased, but avoids to
recompile source JSP document when composed JSP/HTML documents are
modified.
Note: Both "include directive" and "jsp:include" are used in "Composite View" design
pattern Especially while developing portal pages.

3) <jsp:useBean id="object_ref" class="beans.DeptBean" type="java.lang.Object" 3) <jsp:useBean id="object_ref" class="beans.DeptBean" type="java.lang.Object" 3) <jsp:useBean id="object_ref" class="beans.DeptBean" type="java.lang.Object" 3) <jsp:useBean id="object_ref" class="beans.DeptBean" type="java.lang.Object"
scope="page|request|session|application"> scope="page|request|session|application"> scope="page|request|session|application"> scope="page|request|session|application">
This element is used to invoke JavaBean from JSP document without writing
java statements
Class attribute takes which bean class want to be instantiated
Type attribute takes the common/base class of java bean if it is pertaining to
any category
Id attribute holds the object reference name of the bean
Scope attribute takes in which scope among the available 4 scopes of the web
application the object want to be stored
o To store there are two options
request.setAttribute("CONN, con);
pageContext.setAttribute("CONN, con,
pageContext.REQUEST_ATTRIBUTE);
o To retrieve two options available
Connection con=(Connection)request.getAttribute("CONN);
Connection
con=(Connection)pageContext.getAttribute("CONN),
pageContext.REQUEST_ATTRIBUTE);

4) <jsp:setProperty name="obj_ref" property="deptNo" value="10"/> 4) <jsp:setProperty name="obj_ref" property="deptNo" value="10"/> 4) <jsp:setProperty name="obj_ref" property="deptNo" value="10"/> 4) <jsp:setProperty name="obj_ref" property="deptNo" value="10"/>
This element invokes setXXX() function on request property. Must be always used as
a sub element of <jsp:useBean>

5) <jsp:getProperty name="obj_ref" property="dname"/> 5) <jsp:getProperty name="obj_ref" property="dname"/> 5) <jsp:getProperty name="obj_ref" property="dname"/> 5) <jsp:getProperty name="obj_ref" property="dname"/>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 13
This element is used to invoke getXXX() function on specified property. This element
also must be used only as a sub element of jsp:useBean

6) <jsp:plugin type="bean|applet" 6) <jsp:plugin type="bean|applet" 6) <jsp:plugin type="bean|applet" 6) <jsp:plugin type="bean|applet" class="LoginFormApplet" codebase="" width="" class="LoginFormApplet" codebase="" width="" class="LoginFormApplet" codebase="" width="" class="LoginFormApplet" codebase="" width=""
height="" alt="" align=""> height="" alt="" align=""> height="" alt="" align=""> height="" alt="" align="">
This element is used to invoke Applet/Visual Java Beans (but not data access beans)
on JSP document

7) <jsp:fallback/> 7) <jsp:fallback/> 7) <jsp:fallback/> 7) <jsp:fallback/>
This element is used to display alternative text when requested applet executes on
browser.

8) <jsp:param name="" value=""/> 8) <jsp:param name="" value=""/> 8) <jsp:param name="" value=""/> 8) <jsp:param name="" value=""/>
This element must be used as a sub element of <jsp:params>

9) <jsp:params/> 9) <jsp:params/> 9) <jsp:params/> 9) <jsp:params/>
This element must be used as a sub element of <jsp:forward>, <jsp:include> and
<jsp:plugin>

Implicit objects Implicit objects Implicit objects Implicit objects
There are 8 Implicit Objects in JSP File. They are as follows in table Format
Object Object Object Object Name Name Name Name Description Description Description Description
page page page page Is an instance of Object class refs to
current class
instance
config config config config Is an instance of ServletConfig
request request request request HttpServletRequest class instance
response response response response HttpServletResponse class instance
session session session session HttpSession class instance
out out out out JspWriter class instance. Used for writing
stream of characters on STDOUT/browser
application application application application ServletContext class instance
exception exception exception exception Throwable class instance
pageContext pageContext pageContext pageContext Javax.servlet.jsp.PageContext class
instance. This class instance encapsulates
all the above said objects wrapped into
one single object so that these objects
can be used by non-web applications also
such as POJOs, TagLib implementation
and other java classes

Scope variables Scope variables Scope variables Scope variables
There are 4 Scope Variables in JSP Document. They are shown as follows in Table
Format

Scope Scope Scope Scope Description Description Description Description
page scope page scope page scope page scope vars stored in this are available until
the control leaves from existing JSP
document
request scope request scope request scope request scope vars stored in this scope remain
exist until the response came on to
client's browser system
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 14
session scope session scope session scope session scope until session exist
application scope application scope application scope application scope as long as web component is
available in the web server/until the
web component is deployed
/undeployed from the web server

First application First application First application First application
The intention of this application is to show you the basic for writing, deploying and
executing JSP document in TOMCAT

<! <! <! <!-- -- -- -- Hello.jsp Hello.jsp Hello.jsp Hello.jsp -- -- -- --> >> >
<%@ page import=java.util.*%>
<%! Date d=new Date();%>
<%=Hello todate is : "+d.toString()%>

Deployment directory Deployment directory Deployment directory Deployment directory
%TOMCAT_HOME%\webapps\ROOT\

URL: URL: URL: URL:
http://localhost:8080/Hello.jsp

Second application Second application Second application Second application
Topics covered in this application are:
Configuring CP in Tomcat web server (server.xml)
Configuring CP object in web DD file (web.xml)
Retrieving connection object from CP in listener/Servlet class

Development directory Development directory Development directory Development directory
%USER_HOME% %USER_HOME% %USER_HOME% %USER_HOME%\ \\ \adv adv adv adv\ \\ \jsp jsp jsp jsp\ \\ \jdbccpm jdbccpm jdbccpm jdbccpm
JDBCCPM.jsp JDBCCPM.jsp JDBCCPM.jsp JDBCCPM.jsp
\ \\ \WEB WEB WEB WEB- -- -INF INF INF INF\ \\ \web.xml web.xml web.xml web.xml

Create jd Create jd Create jd Create jdbccpm.war file and it into Tomcat and run URL as below bccpm.war file and it into Tomcat and run URL as below bccpm.war file and it into Tomcat and run URL as below bccpm.war file and it into Tomcat and run URL as below

URL: URL: URL: URL:
http://localhost:8080/jdbccpm/JDBCCPMTest.jsp http://localhost:8080/jdbccpm/JDBCCPMTest.jsp http://localhost:8080/jdbccpm/JDBCCPMTest.jsp http://localhost:8080/jdbccpm/JDBCCPMTest.jsp

server.dtd server.dtd server.dtd server.dtd
(This file is given for the knowledge to the students before updating ser (This file is given for the knowledge to the students before updating ser (This file is given for the knowledge to the students before updating ser (This file is given for the knowledge to the students before updating server.xml file ver.xml file ver.xml file ver.xml file
and it is also recommended to take the backup of this file before the file gets and it is also recommended to take the backup of this file before the file gets and it is also recommended to take the backup of this file before the file gets and it is also recommended to take the backup of this file before the file gets
modified) modified) modified) modified)

<!ELEMENT server (Listener*, GlobalNamingResources, Service+)>
<!ELEMENT GlobalNamingResources (Environment*, Resource*, ResourceParams*)>
<!ELEMENT Service (Connector*, Engine*, )>
<!ELEMENT Engine (Logger, Value*, Realm*, Host*)>
<!ELEMENT Host (Cluster*, Value*, Context*)>
<!ELEMENT Cluster (Membership, Receiver, Sender, Value, Deployer)>
<!ELEMENT Context (Logger, Resource*, ResourceParams*)>
<!ELEMENT ResourceParams (parameter*)>
<!ELEMENT parameter (name, value)>

<!ELEMENT Resource EMPTY>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 15
<!ELEMENT name (#PCDATA)>
<!ELEMENT value (#PCDATA)>

d: d: d: d:\ \\ \Program Files Program Files Program Files Program Files\ \\ \ Apache Software Foundation Apache Software Foundation Apache Software Foundation Apache Software Foundation\ \\ \Tomcat 5.0 Tomcat 5.0 Tomcat 5.0 Tomcat 5.0\ \\ \conf conf conf conf\ \\ \server.xml server.xml server.xml server.xml
<server>
<Listener> </Listener>
<Listener> </Listener>

<GlobalNamingResources>
<Enviroment> </Enviroment>
<Resource> </Resource>
<ResourceParams> </ResourceParams>
</GlobalNamingResources>

<Service name=catalina>
<Connector> </Connector>
<Connector> </Connector>
<Connector> </Connector>
<Connector> </Connector>

<Engine name="Standalone"> </Engine>
<Engine name="Catalina" defaultHost="localhost" debug="0">
<Logger>
<Realm>
<Realm>
<Host name="localhost" appBase="webapps" unpackWars="true"
autoDeploy="true">
<Context path="/jdbccpm" docBase="jdbccpm" debug="5" reloadable="true"
crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_jdbccpm_log." suffix=".txt" timestamp="true"/>

<Resource name="jdbc/mysqlPool"
auth="Container"
type="javax.sql.DataSource"/>

<ResourceParams name="jdbc/mysqlPool">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
<! <! <! <!-- -- -- -- T TT The above used .class file is available in he above used .class file is available in he above used .class file is available in he above used .class file is available in
%TOMCAT_HOME% %TOMCAT_HOME% %TOMCAT_HOME% %TOMCAT_HOME%\ \\ \common common common common\ \\ \lib lib lib lib\ \\ \commons commons commons commons- -- -dbcp.jar file. Pl dbcp.jar file. Pl dbcp.jar file. Pl dbcp.jar file. Please ease ease ease make sure that the make sure that the make sure that the make sure that the
.jar file is updated in TOMCAT CLASSPATH setting .jar file is updated in TOMCAT CLASSPATH setting .jar file is updated in TOMCAT CLASSPATH setting .jar file is updated in TOMCAT CLASSPATH setting -- -- -- --> >> >
</parameter>

<! <! <! <!-- -- -- -- Maximum number of Maximum number of Maximum number of Maximum number of D DD DB connections in B connections in B connections in B connections in the the the the pool. Make sure you pool. Make sure you pool. Make sure you pool. Make sure you conf conf conf configure your igure your igure your igure your
mysqld max_connections large enough to handle all of your db connections. Set to 0 mysqld max_connections large enough to handle all of your db connections. Set to 0 mysqld max_connections large enough to handle all of your db connections. Set to 0 mysqld max_connections large enough to handle all of your db connections. Set to 0
for no limit. for no limit. for no limit. for no limit.
-- -- -- --> >> >
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 16

<! <! <! <!-- -- -- -- Maximum number of idle dB connections to retain Maximum number of idle dB connections to retain Maximum number of idle dB connections to retain Maximum number of idle dB connections to retain in pool. in pool. in pool. in pool. Set to 0 for no Set to 0 for no Set to 0 for no Set to 0 for no
limit. limit. limit. limit. -- -- -- --> >> >
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>

<! <! <! <!-- -- -- -- Maximum time to wait for a dB connection to become available Maximum time to wait for a dB connection to become available Maximum time to wait for a dB connection to become available Maximum time to wait for a dB connection to become available in ms, in this in ms, in this in ms, in this in ms, in this
example 10 seconds. An Exception is thrown if this t example 10 seconds. An Exception is thrown if this t example 10 seconds. An Exception is thrown if this t example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to imeout is exceeded. Set to imeout is exceeded. Set to imeout is exceeded. Set to - -- -1 to 1 to 1 to 1 to
wait indefinitely. wait indefinitely. wait indefinitely. wait indefinitely. -- -- -- --> >> >
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>

<! <! <! <!-- -- -- -- MySQL dB username and password for dB connections MySQL dB username and password for dB connections MySQL dB username and password for dB connections MySQL dB username and password for dB connections -- -- -- --> >> >
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value>active</value>
</parameter>

<! <! <! <!-- -- -- -- Class name for mm.mysql JDBC driver Class name for mm.mysql JDBC driver Class name for mm.mysql JDBC driver Class name for mm.mysql JDBC driver -- -- -- --> >> >
<parameter>
<name>driverClassName</name>
<value>sun.jdbc.odbc.JdbcOdbcDriver</value>
</parameter>

<! <! <! <!-- -- -- -- The JDBC connection url for connecting to your MySQL dB. The JDBC connection url for connecting to your MySQL dB. The JDBC connection url for connecting to your MySQL dB. The JDBC connection url for connecting to your MySQL dB. The The The The
autoReconnect=true argument to the url makes sure that the autoReconnect=true argument to the url makes sure that the autoReconnect=true argument to the url makes sure that the autoReconnect=true argument to the url makes sure that the mm.mysql JDBC Driver mm.mysql JDBC Driver mm.mysql JDBC Driver mm.mysql JDBC Driver
will automatically reconnect if mysqld closed the will automatically reconnect if mysqld closed the will automatically reconnect if mysqld closed the will automatically reconnect if mysqld closed the c cc connection. mys onnection. mys onnection. mys onnection. mysqld by default qld by default qld by default qld by default
closes idle connections after 8 hours. closes idle connections after 8 hours. closes idle connections after 8 hours. closes idle connections after 8 hours. -- -- -- --> >> >
<parameter>
<name>url</name>
<value>jdbc:odbc:mysqlDSN</value>
</parameter>
</ResourceParams>
</Context >
</Host>
</Engine>
</Service>
</Server>

web.xml web.xml web.xml web.xml
<web-app>
<listener>
<servlet>
<servlet-mapping>
<welcome-file-list>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 17
<resource <resource <resource <resource- -- -ref> ref> ref> ref>
<res <res <res <res- -- -ref ref ref ref- -- -name>jdbc/ name>jdbc/ name>jdbc/ name>jdbc/mysqlPool mysqlPool mysqlPool mysqlPool</res </res </res </res- -- -ref ref ref ref- -- -name> name> name> name>
<res <res <res <res- -- -type>javax.sql.DataSource</res type>javax.sql.DataSource</res type>javax.sql.DataSource</res type>javax.sql.DataSource</res- -- -type> type> type> type>
<res <res <res <res- -- -auth>Container</res auth>Container</res auth>Container</res auth>Container</res- -- -auth> auth> auth> auth>
<res <res <res <res- -- -sharing sharing sharing sharing- -- -scope>Shareable</res scope>Shareable</res scope>Shareable</res scope>Shareable</res- -- -sharing sharing sharing sharing- -- -scope> scope> scope> scope>
</resource </resource </resource </resource- -- -ref> ref> ref> ref>
</web-app>
*/ */ */ */

<! <! <! <!-- -- -- -- JDBCCPMTest.jsp JDBCCPMTest.jsp JDBCCPMTest.jsp JDBCCPMTest.jsp -- -- -- --> >> >
<%@ page import=javax.naming.*,javax.sql.*, java.sql.*, java.util.*%>
<%! Context ctxt; %>
<%! DataSource ds; %>
<%! Connection con; %>
<%! Statement stmt; %>

<%
try {

ctxt=new InitialContext();
ds=(DataSource)ctxt.lookup("java:comp/env/jdbc/mysqlPool");

// java:comp/ref ref ref ref- -- -name name name name - is used if any J2EE component wants to make lookup
request on server
// java:comp/env/ref ref ref ref- -- -name name name name - is used to request their container processes

con=ds.getConnection();
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM categories");

while(rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}// while()
rs.close(); stmt.close();

}// try
catch(Exception e) { e.printStackTrace(); }
%>

Composite View Composite View Composite View Composite View
Nearly all modern object-oriented development environments support three key
objects for GUI development:
components,
containers,
and layout managers.

Components represent graphic objects such as text, buttons, or lists.
Containers maintain component lists,
while layout managers position and size (or lay out) a container's components.

ActiveNET

JSP chapter
Digital Book www.activenetindia.com 18
Developers typically implement components and containers with the GOF Composite
design pattern, which lets you compose graphical objects into tree hierarchies.
Meanwhile, layout managers are typically implemented with the GOF Strategy design
pattern, so that you can change a container's layout strategy at runtime without
changing the container itself. For its part, the J2EE Composite View design pattern
acts as a recipe for components, containers, and layout managers for JSP-based Web
applications.

At the low end, the Composite View pattern resembles the GOF Composite pattern.
In describing the Composite View pattern in Core J2EE Design Patterns, Alur, Crupi,
and Malks write, "Use composite views that are composed of multiple atomic
subviews...," which means your views should be composites that can contain other
views -- an endorsement of the GOF Composite pattern. Those views can be
composites also, so you can arrange views in a tree hierarchy.

At the high end, the Composite View pattern details the steps necessary to
implement components, containers, and layout managers. The authors continue:
Each component of the template may be included dynamically into the whole, and
the layout of the page may be managed independently of the content.

Difference between static and dynamic attachment of views to JSP document Difference between static and dynamic attachment of views to JSP document Difference between static and dynamic attachment of views to JSP document Difference between static and dynamic attachment of views to JSP document
Static include <%@ include file=doc_url%>
Dynamic include <jsp:include page=doc_url/>

<%@ include %> <%@ include %> <%@ include %> <%@ include %> <jsp:include/> <jsp:include/> <jsp:include/> <jsp:include/>
The code written in the document will be
embedded in JSP document at JSP
translation time into Servlet program
No document source code is include in
the JSP during page translation time
Since code of all HTML documents are
updated at compilation time execution
directly shows output
All participant documents O/Ps are
included in the main JSP document O/P
at runtime so that it is dynamic
Compared with dynamic include here
execution is faster because of compile
time binding
Compared with static execution is slow
because of runtime binding
Preferable when updations in participant
views are now and then
Preferable when updations in participant
views are often
Preferable when participant views are
HTML
Preferable when participant views are
JSPs

Third application Third application Third application Third application
Example on composite view Example on composite view Example on composite view Example on composite view
<! <! <! <!-- -- -- -- Header.html Header.html Header.html Header.html -- -- -- --> >> >
<HTML>
<BODY>
<H1><CENTER>Digital Book</CENTER></H1>

<! <! <! <!-- -- -- -- Menu.html Menu.html Menu.html Menu.html -- -- -- --> >> >
<UL>
<LI>Home</LI>
<LI>What Digital?</LI>
<LI>Why Digital?</LI>
<LI>About U</LI>
<LI>Contact Us</LI>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 19
</UL>

<! <! <! <!-- -- -- -- Body.html Body.html Body.html Body.html -- -- -- --> >> >
<CENTER> Welcome to our site </CENTER>

<! <! <! <!-- -- -- -- Footer.html Footer.html Footer.html Footer.html -- -- -- --> >> >
<CENTER><H6>Copyrights reserved to ActiveNET &r; 2006 - 3006
</H6></CENTER>
</BODY></HTML>

<% <% <% <%-- -- -- -- CompositeViewDemo.jsp CompositeViewDemo.jsp CompositeViewDemo.jsp CompositeViewDemo.jsp -- -- -- --%> %> %> %>
<TABLE>
<TR colspan="2">
<TH><%@ include file="./Header.html"%></TH>
</TR>
<TR>
<TH width="20%"><%@include file="./Menu.html"%></TH>
<TH><jsp:include page="./Body.html"/></TH>
</TR>
<TR>
<TH colspan="2"><jsp:include page="./Footer.html"/></TH>
</TR>
</TABLE>

Take a sma Take a sma Take a sma Take a small assignment ll assignment ll assignment ll assignment
Find out the difference between <%@ include %> <%@ include %> <%@ include %> <%@ include %> (Pronounced as include directive)
and <jsp:include> <jsp:include> <jsp:include> <jsp:include>

Write few lines about it

JSP Model1 Architecture JSP Model1 Architecture JSP Model1 Architecture JSP Model1 Architecture


1. 1. 1. 1. Sends Request from Browser to JSP
2. 2. 2. 2. Creates new instance of Java Bean
3. 3. 3. 3. Retrieves data from Database
4. 4. 4. 4. Sends response back to Client

In Model 1 Architecture the target of every request is a JSP Page. This Page is
Completely Responsible for doing all the tasks required for fulfilling the request. This
JSP
(View)
JavaBeans
DB
Browser
1
4
3
2
Client
Application Server
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 20
includes Authenticating the Client, using Java Beans to Access the Data, managing
the state of the User and so on..

The Main Drawbacks of the Model 1 Architecture are...
First it requires big chunks of business logic which creates a problem to the
Web Page Developers who are not Comfort with Server-Side Programming.
Second is this approach does not provide reusability of Application
components i.e.; for Example a Code written in one JSP Page cant be used in
the other JSP Pages
JSP is not so comfortable for implementing init() and destroy() operations
hence initialization and destruction of variables becomes some what inflexible

Fourth Fourth Fourth Fourth application application application application
Simple Example on JSP Model1 Architecture: Simple Example on JSP Model1 Architecture: Simple Example on JSP Model1 Architecture: Simple Example on JSP Model1 Architecture:

Description Description Description Description: This Example Demonstrates the Example on Inserting & Retrieving Data
from the Database using Model1

Code Code Code Code:
EmpQuery.html EmpQuery.html EmpQuery.html EmpQuery.html
<html>
<form action ="./empQuery.jsp">
<body>
<pre>
Enter Empno:<input type="text" name="empNo">
<input type ="submit" name="submit" value="submit">
</pre>
</body>
</form>
</html>

EmpQuery.jsp EmpQuery.jsp EmpQuery.jsp EmpQuery.jsp
<%
int empNo= Integer.parseInt (request.getParameter("empNo") .trim());
System.out.println("value read:"+empNo);
%>
<jsp:useBean id="bean" class="beans.empBean" scope="request">
<%-- Try this example for 4 times by changing each scope
page|request|session|application. As and when scope changes, change the scope of
access in the below program also.
--%>
<jsp:setProperty name="bean" property="empNo" value='<%=empNo%>'/>
<jsp:getProperty name="bean" property="empName"/>
<jsp:getProperty name="bean" property="desg"/>
<jsp:getProperty name="bean" property="sal"/>
</jsp:useBean>
<jsp:forward page="./display.jsp"/>

Display.jsp Display.jsp Display.jsp Display.jsp
<%
Object o= pageContext.getAttribute("bean", pageContext.REQUEST_SCOPE);
beans.empBean bean=(beans.empBean)o;
%>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 21
<%= bean.getEmpNo()%><br>
<%= bean.getEmpName()%><br>
<%= bean.getDesg()%><br>
<%= bean.getSal()%><br>
<%
pageContext.removeAttribute("bean",pageContext.SESSION_SCOPE);
%>

EmpBean.java EmpBean.java EmpBean.java EmpBean.java
package beans;
import java.io.*;
import java.sql.*;
public class EmpBean implements Serializable
{
private int empNo;
private String empName;
private String desg;
private double sal;
public empBean()
{
}
public void setEmpNo(int no)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con
=DriverManager.getConnection("jdbc:odbc:jadi");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from emp where
empNo="+no);
if(rs.next())
{
empNo=rs.getInt(1);
empName=rs.getString(2);
desg=rs.getString(3);
sal=rs.getDouble(4);
}
rs.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public int getEmpNo()
{
return empNo;
}
public void setEmpName(String abc)
{
empName=abc;
}
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 22
public String getEmpName()
{
return empName;
}
public void setDesg(String des)
{
desg=des;
}
public String getDesg()
{
return desg;
}

public void setSal(double i)
{
sal=i;
}
public double getSal()
{
return sal;
}
}

JSP Model2 Architecture JSP Model2 Architecture JSP Model2 Architecture JSP Model2 Architecture


1. 1. 1. 1. Sends Request from Browser to Servlet
2. 2. 2. 2. Creates new instance Java Bean
3. 3. 3. 3. Retrieves data from Database, Control returned back to Servlet
4. 4. 4. 4. Controller then invokes JSP
5. 5. 5. 5. JSP populates information retrieved from the JavaBeans
6. 6. 6. 6. The final output goes to browser

This Architecture follows the MVC (Model-View-Controller) Architecture. In this
Architecture, the Targets of all the requests are Servlets that acts as the Controller
Servlet
(Controller)
JSP
(View)
JavaBeans

DB
Browser
1
6
5
2
3 4
Client
Application Server
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 23
for the Application. They analyze the Request and collect the data required to
generate a Response into JavaBeans objects which acts as the Model for the
Application. Finally the Controller Servlet dispatches the Request to JSP Pages. These
Pages uses the data stored n the JSP pages to generate the Response. Thus the JSP
pages forms the View of this Architecture.

The main Advantages of this Architecture are.....
There will be very clear Separation of Responsibilities.
There will be very clear maintenance of Applying Security Constraints and
State management issues.
JSP Pages does not require any Complex Business logic Java Code.
This provides chance for the web developers only to work with presentation
of Data.

Fifth Fifth Fifth Fifth application application application application
For this the best example could be replacing all the view Servlet classes in
ShoppingCartMVC example with JSP (CategoriesView.jsp, ProductsView.jsp). If views
changes the forward path in the controller must also be changed to JSP as shown
below:
CategoryController.java
sctxt.getRequestDispatcher("/CategoriesView.jsp).forward(hreq,
hresp);
ProductController.java
sctxt.getRequestDispatcher("/ProductsView.jsp).forward(hreq,
hresp);

J JJ JSP Beans Vs Custom Tags: SP Beans Vs Custom Tags: SP Beans Vs Custom Tags: SP Beans Vs Custom Tags:
1) 1) 1) 1)
JSP Beans are used to separate model operations from JSP document
Custom tags are used to separate model, business logic, control flow of
execution and dynamic/static (optionally) content from JSP document
2) 2) 2) 2)
Even though we can implement user defined functions in JSP bean there is no
default option available in JSP document to access user defined functions of
the bean class except by making explicit call to the method
When accessing custom tag so many lifecycle functions are executed by JSP
container process, hence from one of the lifecycle function we can access user
defined function.
3) 3) 3) 3)
JSP Bean cannot access implicit objects of JSP document, hence it redirects
the response back to JSP document the same should back to client system
JSP custom tags can access all 8 implicit objects of JSP document by getting
only pageContext object share which is given by JSP container during tag
lifecycle execution

Custom Tags Custom Tags Custom Tags Custom Tags
A custom tag is a user-defined JSP language element. When a JSP page containing a
custom tag is translated into a Servlet, the tag is converted to operations on a tag
handler. The Web container then invokes those operations when the JSP page's
Servlet is executed.

Custom Tags do not introduce any new syntax. They are similar to the standard JSP
actions and follow the same XML Syntax format. In that sense, it may be more
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 24
accurate to refer to them as actions actions actions actions rather than tags. tags. tags. tags. Custom Tags allows us to
move the presentation logic outside the JSP pages into Independent Java Classes
called TagHandlers TagHandlers TagHandlers TagHandlers, thereby centralizing the implementation of the Presentation logic
and increasing maintainability. By using customs tags in JSP page instead of scriplets
we can avoid the duplicating the presentation logic, removing the scriptlets also
makes the page less cluttered and easier and easier to read.
Custom tags have a rich set of features. They can:
Be customized via attributes passed from the calling page.
Pass variables back to the calling page.
Access all the objects available to JSP pages.
Communicate with each other. You can create and initialize a JavaBeans
component, create a public EL variable that refers to that bean in one tag,
and then use the bean in another tag.
Be nested within one another and communicate via private variables.
Common Common Common Common terms terms terms terms used in Custom Tags are used in Custom Tags are used in Custom Tags are used in Custom Tags are
1) Tag Handler 1) Tag Handler 1) Tag Handler 1) Tag Handler
The JSP Specification defines a Tag Handler as a runtime, container-managed object
that evaluates custom actions during the execution of a JSP Page.
A Tag Handler is a Normal Java Class that implements one of the 4 interfaces. They
are as follows
Tag
IterationTag
BodyTag
SimpleTag
While executing a JSP file, if the JSP engine encounters a custom tag, it calls the
method on the tags handler class to do the actual work.

2) Tag Library 2) Tag Library 2) Tag Library 2) Tag Library
The JSP Specification defines a Tag Library as a collection of actions that encapsulate
some functionality to be used from within a JSP page.

Typically, we would not prepare just one tag to fulfill a particular requirement.
Rather we would design a set of custom tags that work together and help solve a
recurring requirement. Such a set of custom tags is called Tag Library.

3) Tag Library Descriptor 3) Tag Library Descriptor 3) Tag Library Descriptor 3) Tag Library Descriptor
When we use a custom tags in a JSP page, the JSP engine needs to know the tag
handler classes for theses tags, in which tag library they are location and how are
they used. This meta-information is stored in a file called the Tag Library Descriptor
(TLD).

Using Custom Tags in JSP Pages: Using Custom Tags in JSP Pages: Using Custom Tags in JSP Pages: Using Custom Tags in JSP Pages:
In Order to use Custom tags in a JSP File we have Import those tags using taglib taglib taglib taglib
directive.

We can use different types of Custom Tags in JSP Page. These types include
Empty Tags Empty Tags Empty Tags Empty Tags
Ex:<tag:tagName><tag:tagName/> or <tag:tagName/>
Tags with Attributes Tags with Attributes Tags with Attributes Tags with Attributes
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 25
Ex:<tag:tagName attName=<value>/>
Tags with JSP code Tags with JSP code Tags with JSP code Tags with JSP code
Ex:<test:if condition=true>
Name is :<%=request.getParameter("Name)%>
</test:if>
Tags with nested tags Tags with nested tags Tags with nested tags Tags with nested tags
Ex:
<test:switch conditionValue=<%=request.getAttribute("val)%>> <test:switch conditionValue=<%=request.getAttribute("val)%>> <test:switch conditionValue=<%=request.getAttribute("val)%>> <test:switch conditionValue=<%=request.getAttribute("val)%>>
<test:case caseValue=sayHello>
Hello!
</test:case>
<test:case caseValue=sayBye>
Bye!
</test:case>
</test:switch> </test:switch> </test:switch> </test:switch>


































Sample View of a Custom Tag Component Sample View of a Custom Tag Component Sample View of a Custom Tag Component Sample View of a Custom Tag Component
JSPTag JSPTag JSPTag JSPTag
Tag Tag Tag Tag
Iteration Iteration Iteration IterationTag Tag Tag Tag
Body Body Body BodyTag Tag Tag Tag
Tag Tag Tag TagSupport Support Support Support
Body Body Body BodyTag Tag Tag TagSupport Support Support Support
Serves as a base class for Tag
and SimpleTag. This is mostly for
organizational and type-safety
purposes.
The Tag interface defines the
basic protocol between a Tag
handler and JSP page
implementation class. It defines
the life cycle and the methods to
be invoked at start and end tag.
One additional method that
controls the reevaluation of its
body.
A base class for defining new tag
handlers implementing Tag.
A base class for defining tag
handlers implementing BodyTag.
The BodyTag interface extends IterationTag
by defining additional methods that let a tag
handler manipulate the content of evaluating
its body.
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 26


Taglib Lifecycle Taglib Lifecycle Taglib Lifecycle Taglib Lifecycle

























JSP Page/
PageCompiledServlet
TagHandler /
TagSupport
subclass
setPageContext(pageContext)
setParent(parentTag)
setXXX(val) for each attribute
doStartTag()
doAfterBody()
doEndTag()
release()
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 27
Since you know for each tag developer must provide one sub class of
TagHandler
When user defined tag is invoked on JSP document, page compiled servlet will
first instantiate TagHandler class with the help of default constructor default constructor default constructor default constructor / / / / no arg no arg no arg no arg
constructor constructor constructor constructor
o Constructor() Constructor() Constructor() Constructor()
Next the JSP page compiled servlet sends all the eight implicit objects eight implicit objects eight implicit objects eight implicit objects of JSP
into TagHandler TagHandler TagHandler TagHandler class as a single object called PageContext PageContext PageContext PageContext (PageContext object (PageContext object (PageContext object (PageContext object
holds / wrapper for all 8 implicit objects of JSP) holds / wrapper for all 8 implicit objects of JSP) holds / wrapper for all 8 implicit objects of JSP) holds / wrapper for all 8 implicit objects of JSP). . . .
o setPageContext(PageContext) setPageContext(PageContext) setPageContext(PageContext) setPageContext(PageContext)
Then first lifecycle function of TagHandler executes
o doStartTag()
next doAfterBody()
and then next doEndTag()
finally release()

Purpose of PageContext object Purpose of PageContext object Purpose of PageContext object Purpose of PageContext object
In JSP and servlets the kind of applications today are the communication between
web web web web (Servlets, JSP, Filters) (Servlets, JSP, Filters) (Servlets, JSP, Filters) (Servlets, JSP, Filters) and non web non web non web non web components (POJO/JavaBean, DAO, EJB (POJO/JavaBean, DAO, EJB (POJO/JavaBean, DAO, EJB (POJO/JavaBean, DAO, EJB
etc) etc) etc) etc). During this paradigm/ model some implicit objects of JSP are needed in non
web components. PageContext class stores all the 8 implicit objects of JSP into a
single object passed into every non web component wherever the implicit objects are
required.

Sixth Sixth Sixth Sixth application application application application
/ // /* ** *
HelloDate.jsp HelloDate.jsp HelloDate.jsp HelloDate.jsp
\ \\ \WEB WEB WEB WEB- -- -INF INF INF INF\ \\ \
web.xml web.xml web.xml web.xml
date.tld date.tld date.tld date.tld
\ \\ \classes classes classes classes\ \\ \utils utils utils utils\ \\ \
DateTag.java DateTag.java DateTag.java DateTag.java

Tag preview: Tag preview: Tag preview: Tag preview:
<active:date/> <active:date/> <active:date/> <active:date/>

*/ */ */ */
// DateTag.java // DateTag.java // DateTag.java // DateTag.java
package utils;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class DateTag extends TagSupport
{
public int doStartTag() throws javax.servlet.jsp.JspException
{
java.util.Date date=new java.util.Date();
try
{
JspWriter out=pageContext.getOut();
out.println("Hello.. "+date);
out.close();
}//try
catch(Exception e){}
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 28
return SKIP_BODY;
}// doStartTag()
}// class

.tld file's sample folder: .tld file's sample folder: .tld file's sample folder: .tld file's sample folder:
<! <! <! <!-- -- -- -- date.tld date.tld date.tld date.tld-- -- -- --> >> >
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>date</shortname>
<info>
Sample tag implementation on Empty element
</info>

<tag>
<name>date</name>
<tagclass>utils.DateTag</tagclass>
<bodycontent>empty</bodycontent>
</tag>
</taglib>
<! <! <! <!-- -- -- --web.xml web.xml web.xml web.xml-- -- -- --> >> >
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<taglib>
<taglib-uri>dateuri</taglib-uri> <taglib-location>/WEB-INF/date.tld</taglib-
location>
</taglib>
</web-app>

<! <! <! <!-- -- -- --HelloDate.jsp HelloDate.jsp HelloDate.jsp HelloDate.jsp-- -- -- --> >> >
<%@ taglib uri="dateuri" prefix="active"%>
<active:date/>

http://localhost:7001/datetag/HelloDate.jsp http://localhost:7001/datetag/HelloDate.jsp http://localhost:7001/datetag/HelloDate.jsp http://localhost:7001/datetag/HelloDate.jsp
http://localhost:8080/datetag/HelloDate.jsp http://localhost:8080/datetag/HelloDate.jsp http://localhost:8080/datetag/HelloDate.jsp http://localhost:8080/datetag/HelloDate.jsp

Seventh application
/*
Example on passing attributes into Custom defined tags
<active:dbquery driver="" url="" user="" pass="" query=""/>
*/

DBQueryTest.jsp

\WEB-INF\
web.xml
dbquery.tld

\classes\dbquery\
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 29
DBQueryTag.java

// DBQueryTag.java
package dbquery;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.sql.*;
public class DBQueryTag extends TagSupport
{
String driver, url, user, pass, query;
public void setDriver(String d)
{
driver=d;
}
public void setUrl(String u)
{
url=u;
}
public void setUser(String u)
{
user=u;
}
public void setPass(String p)
{
pass=p;
}
public void setQuery(String q)
{
query=q;
}
public int doStartTag() throws JspException
{
System.out.println("doStartTag()");
try
{
JspWriter out=pageContext.getOut();
Class.forName(driver);
Connection con=DriverManager.getConnection(url, user, pass);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(query);
ResultSetMetaData meta=rs.getMetaData();
int colCount=meta.getColumnCount();
out.println("<HTML><BODY><TABLE border='1'>");
while(rs.next())
{
out.println("<TR>");
for(int i=1;i<=colCount;i++)
{
out.println("<TD>");
out.println(rs.getString(i));
out.println("</TD>");
}// for()
out.println("</TR>");
}// while()
out.println("</TABLE></BODY></HTML>");
out.close();
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 30
}//try
catch(Exception e) {
e.printStackTrace();
}// catch()
return SKIP_BODY;
}// doStartTag()
}// class

dbquery.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>dbquery</shortname>
<info>
This tag populates requested table content on browser.
</info>

<tag>
<name>dbquery</name>
<tagclass>dbquery.DBQueryTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>driver</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>user</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>pass</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>query</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>

web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 31
<taglib>
<taglib-uri>dbqueryuri</taglib-uri>
<taglib-location>/WEB-INF/dbquery.tld</taglib-location>
</taglib>
</web-app>

<!-- DBQueryTest.jsp -->
<%@ taglib uri="dbqueryuri" prefix="db"%>
<db:dbquery driver="sun.jdbc.odbc.JdbcOdbcDriver" url="jdbc:odbc:mydsn"
user="scott" pass="tiger" query='<%=request.getParameter("sql")%>'/>

<!-- DBQueryTest.html -->
<FORM action="./DBQueryTest.jsp">
Enter SELECT <INPUT type="text" name="sql" value="">
<INPUT type="submit" name="submit" value="Click to Query">
</FORM>

/*
http://localhost:7001/dbquery/DBQueryTest.html
http://localhost:8080/dbquery/DBQueryTest.html

SELECT * FROM emp
O/P:
EMPNO ENAME DeptNo
---------------------------------------
2 |XYZ |20 |
---------------------------------------
1 |ABC |10 |
---------------------------------------
*/

Eight application
/*
The following application shows demonstration on nested tag library. This
application is intended to accept source, amt and dest account numbers
from client and updates the TX
Files required:
TransferMoneyForm.html
TransferMoney.jsp
\WEB-INF\
web.xml
tm.tld
\classes\bank\
TransferMoneyTag.java
SourceTag.java
AmtTag.java
DestTag.java
BalanceTag.java

Sample Tag:
<bank:transferMoney datasource="OP" table="account">
<bank:source value="1"/>
<bank:amt value="100"/>
<bank:dest value="2"/>
</bank:transferMoney>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 32

<bank:balance accNo="1"/>
<bank:balance accNo="2"/>
*/

// TransferMoneyTag.java
package bank;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.sql.*;
import java.sql.*;
import javax.naming.*;
import java.util.*;
public class TransferMoneyTag extends TagSupport
{
JspWriter out;
Hashtable ht;
Context ctxt;
DataSource ds;
Connection con;
Statement stmt;
private String datasource, table;
public int source, dest;
public double amt;
boolean flag;

public void setDatasource(String ds)
{
datasource=ds;
}
public void setTable(String t)
{
table=t;
}
public int doStartTag() throws JspException
{
try
{
out=pageContext.getOut();
out.println("<TABLE border="1" align="center">");
}
catch(Exception e){}
return EVAL_BODY_INCLUDE;
}// doStartTag()

public int doAfterBody() throws JspException
{
try
{
ht=new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
ctxt=new InitialContext(ht);
ds=(DataSource)ctxt.lookup(datasource);
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 33
con=ds.getConnection();
stmt=con.createStatement();
pageContext.setAttribute("CONN", con, pageContext.PAGE_SCOPE);
int i=stmt.executeUpdate("update "+table+" set bal=bal-"+amt+" where
accNo="+source);
int j=stmt.executeUpdate("update "+table+" set bal=bal+"+amt+" where
accNo="+dest);
if(i==1 && j==1)
flag=true;
else
flag=false;
stmt.close();
out.println("<TR><TH>TX successful</TH></TR>");
}// try
catch(Exception e){e.printStackTrace();}
return SKIP_BODY;
}// doAfterBody()

public int doEndTag() throws JspException
{
out.println("</TABLE>");
if(flag)
return EVAL_PAGE;
else
return SKIP_PAGE;
}// doEndTag()
}// class

// SourceTag.java
package bank;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class SourceTag extends BodyTagSupport
{
public int doStartTag() throws JspException
{
Tag tag=getParent();
TransferMoneyTag tmtag=(TransferMoneyTag)tag;
tmtag.source=value;
return SKIP_BODY;
}// doStartTag()
int value;
public void setValue(int v)
{
value=v;
}
}// class

// AmtTag.java
package bank;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class AmtTag extends BodyTagSupport
{
private double value;
public void setValue(double v)
{
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 34
value=v;
}
public int doStartTag() throws JspException
{
((TransferMoneyTag)getParent()).amt=value;
return SKIP_BODY;
}
}// class

// DestTag.java
package bank;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class DestTag extends BodyTagSupport
{
private int value;
public void setValue(int v)
{
value=v;
}
public int doStartTag() throws JspException
{
((TransferMoneyTag)getParent()).dest=value;
return SKIP_BODY;
}
}// class

// BalanceTag.java
package bank;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.sql.*;
public class BalanceTag extends TagSupport
{
private int accNo;
public void setAccNo(int a)
{
accNo=a;
}
public int doStartTag() throws JspException
{
try
{
Connection con=(Connection)pageContext.getAttribute("CONN",
pageContext.PAGE_SCOPE);
if(con!=null)
{
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select bal from account where
accNo="+accNo);
if(rs.next())
{
pageContext.getOut().println(accNo+" balance is: "+rs.getDouble(1));
}// if
rs.close();
stmt.close();
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 35
}// if()
}// try
catch(Exception e)
{
e.printStackTrace();
}// catch()
return SKIP_BODY;
}// doStartTag()
}// class

<!--
tm.tld
-->
<tag>
<name>transferMoney</name>
<tagclass>bank.TransferMoneyTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>datasource</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>table</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
<tag>
<name>source</name>
<tagclass>bank.SourceTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
<tag>
<name>amt</name>
<tagclass>bank.AmtTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
<tag>
<name>dest</name>
<tagclass>bank.DestTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 36
</tag>
<tag>
<name>balance</name>
<tagclass>bank.BalanceTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>accNo</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>

<!-- web.xml -->
<web-app>
<taglib>
<taglib-uri>tm-uri</taglib-uri>
<taglib-location>/WEB-INF/tm.tld</taglib-location>
</taglib>
</web-app>

Ninth application
<!-- TransferMoneyForm.html -->
<HTML>
<BODY>
<FORM action="./TransferMoney.jsp">
<TABLE border="10" align="center">
<TR>
<TH>Source</TH>
<TD><INPUT type="text" name="source" value=""></TD>
</TR>
<TR>
<TH>Amount</TH>
<TD><INPUT type="text" name="amt" value=""></TD>
</TR>
<TR>
<TH>Dest</TH>
<TD><INPUT type="text" name="dest" value=""></TD>
</TR>
<TR>
<TD><INPUT type="submit" name="submit" value="Transfer"></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>

<!--TransferMoney.jsp-->
<%@ taglib uri="tm-uri" prefix="bank"%>
<bank:transferMoney datasource="jspPool" table="account">
<bank:source
value='<%=Integer.parseInt(request.getParameter("source").trim())%>'/>
<bank:amt
value="<%=Double.valueOf(request.getParameter(\"amt\").trim()).doubleVa
lue()%>"/>
<bank:dest
value='<%=Integer.parseInt(request.getParameter("dest").trim())%>'/>
ActiveNET

JSP chapter
Digital Book www.activenetindia.com 37
</bank:transferMoney>

<bank:balance accNo="1"/>
<bank:balance accNo="2"/>

http://localhost:7001/tm/TransferMoneyForm.html

<!--
<bank:source
value='<%=Integer.parseInt(request.getParameter("source"))%>'/>
<bank:amt
value='<%=Double.valueOf(request.getParameter("amt").trim()).doubleValu
e()%>'/>
<bank:dest
value='<%=Integer.parseInt(request.getParameter("dest").trim())%>'/>
-->

Vous aimerez peut-être aussi