SlideShare a Scribd company logo
Introduction to JSP
• JSP technology is used to create dynamic web applications. JSP pages are
easier to maintain then a Servlet. JSP pages are opposite of Servlets as a
servlet adds HTML code inside Java code, while JSP adds Java code inside
HTML using JSP tags. Everything a Servlet can do, a JSP page can also do
it.
• JSP enables us to write HTML pages containing tags, inside which we can
include powerful Java programs . Using JSP, one can easily separate
Presentation and Business logic as a web designer can design and update
JSP pages creating the presentation layer and java developer can write
server side complex computational code without concerning the web
design. And both the layers can easily interact over HTTP requests.
In the end a JSP becomes a Servlet
• JSP pages are converted into Servlet by the Web Container. The Container
translates a JSP page into servlet class source(.java) file and then
compiles into a Java Servlet class.
Why JSP is preferred over servlets?
• JSP provides an easier way to code dynamic web pages.
• JSP does not require additional files like, java class files, web.xml etc
• Any change in the JSP code is handled by Web Container(Application
server like tomcat), and doesn't require re-compilation.
• JSP pages can be directly accessed, and web.xml mapping is not required
like in servlets.
Advantage of JSP
• Easy to maintain and code.
• High Performance and Scalability.
• JSP is built on Java technology, so it is platform independent.
Lifecycle of JSP
• A JSP page is converted into Servlet in order to service requests. The translation
of a JSP page to a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same
as the Servlet Lifecycle, with one additional first step, which is, translation of
JSP code to Servlet code. Following are the JSP Lifecycle steps:
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to byte code.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method
EXAMPLE:
• The code written inside <% %> is JSP code<html>
• Hello.jsp
• <html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>.
Creating a JSP Page
• A JSP page looks similar to an HTML page, but a JSP page also has Java
code in it. We can put any regular Java Code in a JSP file using a scriplet
tag which start with <% and ends with %>. JSP pages are used to develop
dynamic responses.
• JSP Scripting Element:
• JSP Scripting element are written inside <% %> tags. These code inside
<% %> tags are processed by the JSP engine during translation of the JSP
page. Any other text in the JSP page is considered as HTML code or plain
text.
There are five different types of scripting elements
Scripting Element Example
Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>
JSP Comment
• JSP Comment is used when you are creating a JSP page and want to put in comments about
what you are doing. JSP comments are only seen in the JSP page. These comments are not
included in servlet source code during translation phase, nor they appear in the HTTP
response. Syntax of JSP comment is as follows :
<%-- JSP comment --%>
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
<%-- Code to show page count --%>
Page Count is <% out.println(++count); %>
</body>
Scriptlet Tag
Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements the
_jspService method functionality by writing script/java code
<% java code %>
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
Mixing scriptlet Tag and HTML
<table border = 1>
<%
for ( int i = 0; i < n; i++ ) {
%>
<tr>
<td>Number</td>
<td><%= i+1 %></td>
</tr>
<%
}
%>
</table>
Declaration Tag
When we declare a variable or method in JSP inside Declaration Tag, it means the declaration is made inside
the Servlet class but outside the service(or any other) method. You can declare static member, instance
variable and methods inside Declaration Tag.
<% ! declaration %>
Example of Declaration Tag
<html>
<head>
<title>My First JSP Page</title>
</head>
<%!
int count = 0;
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>
Directive Tag
• Directive Tag gives special instruction to Web Container at the time of
page translation. Directive tags are of three types: page, include and
taglib.
Directive Description
• <%@ page ... %> defines page dependent properties such as language,
session, errorPage etc.
• <%@ include ... %> defines file to be included.
• <%@ taglib ... %>declares tag library used in the page
The Page directive defines a number of page dependent properties which
communicates with the Web Container at the time of translation. Basic syntax of
using the page directive is <%@ page attribute="value" %> where attributes can be
one of the following :
• import attribute
• language attribute
• extends attribute
• session attribute
• isThreadSafe attribute
• isErrorPage attribute
• errorPage attribute
• contentType attribute
• autoFlush attribute
• buffer attribute
• import attribute
The import attribute defines the set of classes and packages that must be imported in servlet
class definition. For example
<%@ page import="java.util.Date" %>
or
<%@ page import="java.util.Date,java.net.*" %>
language attribute
language attribute defines scripting language to be used in the page.
extends attribute
extends attribute defines the class name of the superclass of the servlet class that is
generated from the JSP page.
session attribute
session attribute defines whether the JSP page is participating in an HTTP session. The value
is either true or false.
isErrorPage attribute
isErrorPage attribute declares whether the current JSP Page represents
another JSP's error page.
errorPage attribute
errorPage attribute indicates another JSP page that will handle all the run
time exceptions thrown by current JSP page. It specifies the URL path of
another page to which a request is to be dispatched to handle run time
exceptions thrown by current JSP page.
Expression Tag
• Expression Tag is used to print out java language expression that is put between the
tags. An expression tag can hold any java language expression that can be used as
an argument to the out.print() method.
<%= JavaExpression %>
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <%= ++count %>
</body>
Implicit Objects in JSP
• JSP provide access to some implicit object which represent some commonly
used objects for servlets that JSP page developers might need to use. For
example you can retrieve HTML form parameter data by using request
variable, which represent the HttpServletRequest object.
• Following are the JSP implicit object
Implicit Object Description
request The HttpServletRequest object associated with the request.
response The HttpServletRequest object associated with the response that is
sent back to the browser.
out The JspWriter object associated with the output stream of the
response.
session The HttpSession object associated with the session for the given user
of request.
application The ServletContext object for the web application.
config The ServletConfig object associated with the servlet for current JSP
page.
pageContext The PageContext object that encapsulates the enviroment of a single
request for this current JSP page
page The page variable is equivalent to this variable of Java programming
language.
exception The exception object represents the Throwable object that was
thrown by some other JSP page.
Include Directive
• The include directive tells the Web Container to copy everything in the
included file and paste it into current JSP file.
Syntax of include directive is:
<%@ include file="filename.jsp" %>
Example of include directive
welcome.jsp
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<%@ include file="header.jsp" %>
Welcome, User
</body>
</html>
header.jsp
<html>
<body>
<img src="header.jpg" alt="This is Header image" / >
</body>
</html>
Taglib Directive
• The taglib directive is used to define tag library that the current JSP page uses.
A JSP page might include several tag library. Java Server Pages Standard Tag
Library (JSTL), is a collection of useful JSP tags, which provides many commonly
used core functionalities. It has support for many general, structural tasks such
as iteration and conditionals, readymade tags for manipulating XML
documents, internationalization tags, and for performing SQL operations.
Syntax of taglib directive is:
<%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>
Using Taglib Directive
To use the JSTL in your application you must have the jstl.jar in your webapps
/WEB-INF/lib directory. Download the jar file from Apache Standard Taglib
page.
There are many readymade JST Libraries available which you use to make your
life easier. Following is a broad division on dufferent groups of JST libraries :
Core Tags - URI → http://java.sun.com/jsp/jstl/core
Formatting Tags - URI → http://java.sun.com/jsp/jstl/fmt
SQL Tags - URI → http://java.sun.com/jsp/jstl/sql
XML Tags - URI → http://java.sun.com/jsp/jstl/xml
JSTL Functions - URI → http://java.sun.com/jsp/jstl/functions
Exception Handling
• Exception Handling is a process of handling exceptional condition that might
occur in your application. Exception Handling in JSP is much easier than Java
Technology exception handling. Although JSP Technology also uses the same
exception class objects.
• It is quite obvious that you dont want to show error stack trace to any random
user surfing your website. You can't prevent all errors in your application but
you can atleast give a user friendly error response page.
• Ways to perform Exception Handling in JSP
JSP provide 3 different ways to perform exception handling:
• Using isErrorPage and errorPage attribute of page directive.
• Using <error-page> tag in Deployment Descriptor.
• Using simple try...catch block.
Example of isErrorPage and errorPage attribute
• isErrorPage attribute in page directive officially appoints a JSP page as an error
page.
• error.jsp
Sum.jsp
• Declaring error page in Deployment Descriptor
You can also declare error pages in the DD for the entire Web Apllication. Using <error-page> tag in the Deployment
Descriptor. You can even configure different error pages for different exception types, or HTTP error code type(503, 500 etc).
• Declaring an error page for all type of exception
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
• Declaring an error page for more detailed exception
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/error.jsp</location>
</error-page>
• Declaring an error page based on HTTP Status code
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
Using the try...catch block
<html>
<head>
<title>Try...Catch Example</title>
</head>
<body>
<%
try{
int i = 100;
i = i / 0;
out.println("The answer is " + i);
}
catch (Exception e)
{
out.println("An exception occurred: " + e.getMessage());
}
%>
</body>
</html>
Standard Tag(Action Element)
• JSP specification provides Standard(Action) tags for use within your JSP
pages. These tags are used to remove or eliminate scriptlet code from
your JSP page because scriplet code are technically not recommended
nowadays. It's considered to be bad practice to put java code directly
inside your JSP page.
• Standard tags begin with the jsp: prefix. There are many JSP Standard
Action tag which are used to perform some specific task.
JSP Standard Action Tags available:
Action Tag Description
jsp:forward forward the request to a new page
Usage : <jsp:forward page="Relative URL" />
jsp:useBean instantiates a JavaBean
Usage : <jsp:useBean id="beanId" />
jsp:getProperty retrieves a property from a JavaBean instance.
Usage :
<jsp:useBean id="beanId" ... /> ... <jsp:getProperty name="beanId" property="someProperty"
.../>
Where, beanName is the name of pre-defined bean whose property we want to access.
jsp:setProperty store data in property of any JavaBeans instance.
Usage :
<jsp:useBean id="beanId" ... /> ... <jsp:setProperty name="beanId" property="someProperty"
value="some value"/>
Where, beanName is the name of pre-defined bean whose property we want to access.
jsp:include includes the runtime response of a JSP page into the current page.
jsp:plugin Generates client browser-specific construct that makes an OBJECT or EMBED tag for the Java
Applets
jsp:fallback Supplies alternate text if java plugin is unavailable on the client. You can print a message
using this, if the included jsp plugin is not loaded.
jsp:element Defines XML elements dynamically
jsp:attribute defines dynamically defined XML element's attribute
jsp:body Used within standard or custom tags to supply the tag body.
jsp:param Adds parameters to the request object.
jsp:text Used to write template text in JSP pages and documents.
Usage : <jsp:text>Template data</jsp:text>
<jsp:forward> Action
<jsp:forward> is used for redirecting the request. When this action is encountered on a JSP page the control gets transferred to the page
mentioned in this action.
Syntax of <jsp:forward> :
<jsp:forward page="URL of the another static, JSP OR Servlet page" />
Example:
first.jsp
<html>
<head>
<title>Demo of JSP Forward Action Tag</title>
</head>
<body>
<h3>JSP page: Demo forward</h3>
<jsp:forward page="second.jsp" />
</body>
</html>
Now when JSP engine would execute first.jsp (the above code) then after action tag, the request would be transferred to another JSP page
(second.jsp).
Note: first.jsp and second.jsp should be in the same directory otherwise you have to specify the complete path of second.jsp.
<jsp:param> Action
This action is useful for passing the parameters to Other JSP action tags such as JSP include & JSP forward tag. This way new JSP pages can have access to those
parameters using request object itself.
Syntax of <jsp:param>:
<jsp: param name="param_name_here" value="value_of_parameter_here"
first.jsp
<html>
<head>
<title>Demo of JSP Param Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Param along with forward</h3>
<jsp:forward page="second.jsp">
<jsp:param name ="date" value="20-05-2012" />
<jsp:param name ="time" value="10:15AM" />
<jsp:param name ="data" value="ABC" />
</jsp:forward>
</body>
</html>
In the above example first.jsp is passing three parameters (data, time & data) to second.jsp and second.jsp can access these parameters using the below code –
Date:<%= request.getParameter("date") %>
Time:<%= request.getParameter("time") %>
My Data:<%= request.getParameter("data") %>
<jsp:include> Action
<jsp:include> vs include directive :
In <jsp:include> the file is being included during request processing while in case of include directive it
has been included at translation phase.
Syntax of <jsp:include> :
<jsp:include page="page URL" flush="Boolean Value" />
Here page URL is: the location of the page needs to be included & flush value can be either true or
false (Boolean value).
Example:
<html>
<head>
<title>Demo of JSP include Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Include</h3>
<jsp:include page="sample.jsp" flush="false" />
</body>
</html>
Java Bean
• A Java Bean is a java class that should follow following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as
getter and setter methods.
• Why use Java Bean?
• According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object, so we can access this object from
multiple places. Moreover, it provides the easy maintenance.
Simple example of java bean class
//Employee.java
package mypack;
public class Employee implements java.io.Serializable
{
private int id;
private String name;
public Employee()
{ }
public void setId(int id)
{this.id=id;}
public int getId()
{return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
Connection Pooling
• Establishing JDBC connections is resource-expensive, especially when the JDBC
API is used in a middle-tier server environment, such as when DataDirect
Connect for JDBC or DataDirect SequeLink for JDBC is running on a Java-enabled
web server. In this type of environment, performance can be improved
significantly when connection pooling is used. Connection pooling means that
connections are reused rather than created each time a connection is requested.
To facilitate connection reuse, a memory cache of database connections, called a
connection pool, is maintained by a connection pooling module as a layer on top
of any standard JDBC driver product.
• Connection pooling is performed in the background and does not affect how an
application is coded; however, the application must use a DataSource object (an
object implementing the DataSource interface) to obtain a connection instead of
using the DriverManager class. A class implementing the DataSource interface
may or may not provide connection pooling. A DataSource object registers with a
JNDI naming service. Once a DataSource object is registered, the application
retrieves it from the JNDI naming service in the standard way.
For example:
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/SequeLink");
If the DataSource object provides connection pooling, the lookup returns a connection from
the pool if one is available. If the DataSource object does not provide connection pooling or if
there are no available connections in the pool, the lookup creates a new connection. The
application benefits from connection reuse without requiring any code changes. Reused
connections from the pool behave the same way as newly created physical connections. The
application makes a connection to the database and data access works in the usual way. When
the application has finished its work with the connection, the application explicitly closes the
connection.
For example:
Connection con = ds.getConnection("scott", "tiger");
// Do some database activities using the connection...
con.close();
The closing event on a pooled connection signals the pooling module to place the connection
back in the connection pool for future reuse.
Jsp
Jsp

More Related Content

What's hot

ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
priya Nithya
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
Ravinder Kamboj
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
Zunair Sagitarioux
 
Introduction to Web Development
Introduction to Web DevelopmentIntroduction to Web Development
Introduction to Web Development
Parvez Mahbub
 
Bootstrap
BootstrapBootstrap
Bootstrap
Jadson Santos
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
1amitgupta
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance TopicsAli Taki
 
Hibernate
HibernateHibernate
Hibernate
Prashant Kalkar
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
kamal kotecha
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
Pihu Goel
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Fragment
Fragment Fragment
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
Partnered Health
 

What's hot (20)

ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
Js ppt
Js pptJs ppt
Js ppt
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
 
Introduction to Web Development
Introduction to Web DevelopmentIntroduction to Web Development
Introduction to Web Development
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Asp Architecture
Asp ArchitectureAsp Architecture
Asp Architecture
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance Topics
 
Hibernate
HibernateHibernate
Hibernate
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Introduction to ajax
Introduction  to  ajaxIntroduction  to  ajax
Introduction to ajax
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Fragment
Fragment Fragment
Fragment
 
Xml http request
Xml http requestXml http request
Xml http request
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 

Viewers also liked

Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
Chitrank Dixit
 
01 session tracking
01   session tracking01   session tracking
01 session trackingdhrubo kayal
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
AshishSingh Bhatia
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
kamal kotecha
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
BG Java EE Course
 
Jsp
JspJsp
J2EE and layered architecture
J2EE and layered architectureJ2EE and layered architecture
J2EE and layered architecture
Suman Behara
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
Salim M
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 
Java Web 5 - JSP, Expression Language e Taglibs
Java Web 5 - JSP, Expression Language e TaglibsJava Web 5 - JSP, Expression Language e Taglibs
Java Web 5 - JSP, Expression Language e TaglibsEduardo Mendes
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
APSMIND TECHNOLOGY PVT LTD.
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java server pages
Java server pagesJava server pages
Java server pages
Tanmoy Barman
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Fahad Golra
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 

Viewers also liked (20)

Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
01 session tracking
01   session tracking01   session tracking
01 session tracking
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Jsp
JspJsp
Jsp
 
J2EE and layered architecture
J2EE and layered architectureJ2EE and layered architecture
J2EE and layered architecture
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java Web 5 - JSP, Expression Language e Taglibs
Java Web 5 - JSP, Expression Language e TaglibsJava Web 5 - JSP, Expression Language e Taglibs
Java Web 5 - JSP, Expression Language e Taglibs
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Exception handling
Exception handlingException handling
Exception handling
 

Similar to Jsp

Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Shah Nawaz Bhurt
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Ayes Chinmay
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
NishaRohit6
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
ManishaPatil932723
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
Yoga Raja
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSJSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODS
bharathiv53
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
Vipin Yadav
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
ShahDhruv21
 
Unit 4 1 web technology uptu
Unit 4 1 web technology uptuUnit 4 1 web technology uptu
Unit 4 1 web technology uptu
Abhishek Kesharwani
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
Abhishek Kesharwani
 
Jsp
JspJsp
Jsp 01
Jsp 01Jsp 01
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
Subhasis Nayak
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
MathivananP4
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorialshiva404
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Raheela Patel
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
BG Java EE Course
 

Similar to Jsp (20)

Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSJSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODS
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
 
Unit 4 1 web technology uptu
Unit 4 1 web technology uptuUnit 4 1 web technology uptu
Unit 4 1 web technology uptu
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
 
Jsp
JspJsp
Jsp
 
Jsp 01
Jsp 01Jsp 01
Jsp 01
 
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java server pages
Java server pagesJava server pages
Java server pages
 

Recently uploaded

HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 

Recently uploaded (20)

HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 

Jsp

  • 1. Introduction to JSP • JSP technology is used to create dynamic web applications. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page can also do it. • JSP enables us to write HTML pages containing tags, inside which we can include powerful Java programs . Using JSP, one can easily separate Presentation and Business logic as a web designer can design and update JSP pages creating the presentation layer and java developer can write server side complex computational code without concerning the web design. And both the layers can easily interact over HTTP requests.
  • 2. In the end a JSP becomes a Servlet • JSP pages are converted into Servlet by the Web Container. The Container translates a JSP page into servlet class source(.java) file and then compiles into a Java Servlet class.
  • 3. Why JSP is preferred over servlets? • JSP provides an easier way to code dynamic web pages. • JSP does not require additional files like, java class files, web.xml etc • Any change in the JSP code is handled by Web Container(Application server like tomcat), and doesn't require re-compilation. • JSP pages can be directly accessed, and web.xml mapping is not required like in servlets.
  • 4. Advantage of JSP • Easy to maintain and code. • High Performance and Scalability. • JSP is built on Java technology, so it is platform independent.
  • 5. Lifecycle of JSP • A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with one additional first step, which is, translation of JSP code to Servlet code. Following are the JSP Lifecycle steps: 1. Translation of JSP to Servlet code. 2. Compilation of Servlet to byte code. 3. Loading Servlet class. 4. Creating servlet instance. 5. Initialization by calling jspInit() method 6. Request Processing by calling _jspService() method 7. Destroying by calling jspDestroy() method
  • 6.
  • 7. EXAMPLE: • The code written inside <% %> is JSP code<html> • Hello.jsp • <html> <head> <title>My First JSP Page</title> </head> <% int count = 0; %> <body> Page Count is: <% out.println(++count); %> </body> </html>.
  • 8. Creating a JSP Page • A JSP page looks similar to an HTML page, but a JSP page also has Java code in it. We can put any regular Java Code in a JSP file using a scriplet tag which start with <% and ends with %>. JSP pages are used to develop dynamic responses. • JSP Scripting Element: • JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are processed by the JSP engine during translation of the JSP page. Any other text in the JSP page is considered as HTML code or plain text.
  • 9. There are five different types of scripting elements Scripting Element Example Comment <%-- comment --%> Directive <%@ directive %> Declaration <%! declarations %> Scriptlet <% scriplets %> Expression <%= expression %>
  • 10. JSP Comment • JSP Comment is used when you are creating a JSP page and want to put in comments about what you are doing. JSP comments are only seen in the JSP page. These comments are not included in servlet source code during translation phase, nor they appear in the HTTP response. Syntax of JSP comment is as follows : <%-- JSP comment --%> Example: <html> <head> <title>My First JSP Page</title> </head> <% int count = 0; %> <body> <%-- Code to show page count --%> Page Count is <% out.println(++count); %> </body>
  • 11. Scriptlet Tag Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements the _jspService method functionality by writing script/java code <% java code %> Example: <html> <head> <title>My First JSP Page</title> </head> <% int count = 0; %> <body> Page Count is <% out.println(++count); %> </body> </html>
  • 12. Mixing scriptlet Tag and HTML <table border = 1> <% for ( int i = 0; i < n; i++ ) { %> <tr> <td>Number</td> <td><%= i+1 %></td> </tr> <% } %> </table>
  • 13. Declaration Tag When we declare a variable or method in JSP inside Declaration Tag, it means the declaration is made inside the Servlet class but outside the service(or any other) method. You can declare static member, instance variable and methods inside Declaration Tag. <% ! declaration %> Example of Declaration Tag <html> <head> <title>My First JSP Page</title> </head> <%! int count = 0; %> <body> Page Count is: <% out.println(++count); %> </body> </html>
  • 14. Directive Tag • Directive Tag gives special instruction to Web Container at the time of page translation. Directive tags are of three types: page, include and taglib. Directive Description • <%@ page ... %> defines page dependent properties such as language, session, errorPage etc. • <%@ include ... %> defines file to be included. • <%@ taglib ... %>declares tag library used in the page
  • 15. The Page directive defines a number of page dependent properties which communicates with the Web Container at the time of translation. Basic syntax of using the page directive is <%@ page attribute="value" %> where attributes can be one of the following : • import attribute • language attribute • extends attribute • session attribute • isThreadSafe attribute • isErrorPage attribute • errorPage attribute • contentType attribute • autoFlush attribute • buffer attribute
  • 16. • import attribute The import attribute defines the set of classes and packages that must be imported in servlet class definition. For example <%@ page import="java.util.Date" %> or <%@ page import="java.util.Date,java.net.*" %> language attribute language attribute defines scripting language to be used in the page. extends attribute extends attribute defines the class name of the superclass of the servlet class that is generated from the JSP page. session attribute session attribute defines whether the JSP page is participating in an HTTP session. The value is either true or false.
  • 17. isErrorPage attribute isErrorPage attribute declares whether the current JSP Page represents another JSP's error page. errorPage attribute errorPage attribute indicates another JSP page that will handle all the run time exceptions thrown by current JSP page. It specifies the URL path of another page to which a request is to be dispatched to handle run time exceptions thrown by current JSP page.
  • 18. Expression Tag • Expression Tag is used to print out java language expression that is put between the tags. An expression tag can hold any java language expression that can be used as an argument to the out.print() method. <%= JavaExpression %> Example: <html> <head> <title>My First JSP Page</title> </head> <% int count = 0; %> <body> Page Count is <%= ++count %> </body>
  • 19. Implicit Objects in JSP • JSP provide access to some implicit object which represent some commonly used objects for servlets that JSP page developers might need to use. For example you can retrieve HTML form parameter data by using request variable, which represent the HttpServletRequest object.
  • 20. • Following are the JSP implicit object Implicit Object Description request The HttpServletRequest object associated with the request. response The HttpServletRequest object associated with the response that is sent back to the browser. out The JspWriter object associated with the output stream of the response. session The HttpSession object associated with the session for the given user of request. application The ServletContext object for the web application. config The ServletConfig object associated with the servlet for current JSP page. pageContext The PageContext object that encapsulates the enviroment of a single request for this current JSP page page The page variable is equivalent to this variable of Java programming language. exception The exception object represents the Throwable object that was thrown by some other JSP page.
  • 21. Include Directive • The include directive tells the Web Container to copy everything in the included file and paste it into current JSP file. Syntax of include directive is: <%@ include file="filename.jsp" %>
  • 22. Example of include directive welcome.jsp <html> <head> <title>Welcome Page</title> </head> <body> <%@ include file="header.jsp" %> Welcome, User </body> </html> header.jsp <html> <body> <img src="header.jpg" alt="This is Header image" / > </body> </html>
  • 23. Taglib Directive • The taglib directive is used to define tag library that the current JSP page uses. A JSP page might include several tag library. Java Server Pages Standard Tag Library (JSTL), is a collection of useful JSP tags, which provides many commonly used core functionalities. It has support for many general, structural tasks such as iteration and conditionals, readymade tags for manipulating XML documents, internationalization tags, and for performing SQL operations. Syntax of taglib directive is: <%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>
  • 24. Using Taglib Directive To use the JSTL in your application you must have the jstl.jar in your webapps /WEB-INF/lib directory. Download the jar file from Apache Standard Taglib page. There are many readymade JST Libraries available which you use to make your life easier. Following is a broad division on dufferent groups of JST libraries : Core Tags - URI → http://java.sun.com/jsp/jstl/core Formatting Tags - URI → http://java.sun.com/jsp/jstl/fmt SQL Tags - URI → http://java.sun.com/jsp/jstl/sql XML Tags - URI → http://java.sun.com/jsp/jstl/xml JSTL Functions - URI → http://java.sun.com/jsp/jstl/functions
  • 25. Exception Handling • Exception Handling is a process of handling exceptional condition that might occur in your application. Exception Handling in JSP is much easier than Java Technology exception handling. Although JSP Technology also uses the same exception class objects. • It is quite obvious that you dont want to show error stack trace to any random user surfing your website. You can't prevent all errors in your application but you can atleast give a user friendly error response page. • Ways to perform Exception Handling in JSP JSP provide 3 different ways to perform exception handling: • Using isErrorPage and errorPage attribute of page directive. • Using <error-page> tag in Deployment Descriptor. • Using simple try...catch block.
  • 26. Example of isErrorPage and errorPage attribute • isErrorPage attribute in page directive officially appoints a JSP page as an error page. • error.jsp
  • 28. • Declaring error page in Deployment Descriptor You can also declare error pages in the DD for the entire Web Apllication. Using <error-page> tag in the Deployment Descriptor. You can even configure different error pages for different exception types, or HTTP error code type(503, 500 etc). • Declaring an error page for all type of exception <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.jsp</location> </error-page> • Declaring an error page for more detailed exception <error-page> <exception-type>java.lang.ArithmeticException</exception-type> <location>/error.jsp</location> </error-page> • Declaring an error page based on HTTP Status code <error-page> <error-code>404</error-code> <location>/error.jsp</location> </error-page>
  • 29. Using the try...catch block <html> <head> <title>Try...Catch Example</title> </head> <body> <% try{ int i = 100; i = i / 0; out.println("The answer is " + i); } catch (Exception e) { out.println("An exception occurred: " + e.getMessage()); } %> </body> </html>
  • 30. Standard Tag(Action Element) • JSP specification provides Standard(Action) tags for use within your JSP pages. These tags are used to remove or eliminate scriptlet code from your JSP page because scriplet code are technically not recommended nowadays. It's considered to be bad practice to put java code directly inside your JSP page. • Standard tags begin with the jsp: prefix. There are many JSP Standard Action tag which are used to perform some specific task.
  • 31. JSP Standard Action Tags available: Action Tag Description jsp:forward forward the request to a new page Usage : <jsp:forward page="Relative URL" /> jsp:useBean instantiates a JavaBean Usage : <jsp:useBean id="beanId" /> jsp:getProperty retrieves a property from a JavaBean instance. Usage : <jsp:useBean id="beanId" ... /> ... <jsp:getProperty name="beanId" property="someProperty" .../> Where, beanName is the name of pre-defined bean whose property we want to access. jsp:setProperty store data in property of any JavaBeans instance. Usage : <jsp:useBean id="beanId" ... /> ... <jsp:setProperty name="beanId" property="someProperty" value="some value"/> Where, beanName is the name of pre-defined bean whose property we want to access. jsp:include includes the runtime response of a JSP page into the current page. jsp:plugin Generates client browser-specific construct that makes an OBJECT or EMBED tag for the Java Applets jsp:fallback Supplies alternate text if java plugin is unavailable on the client. You can print a message using this, if the included jsp plugin is not loaded. jsp:element Defines XML elements dynamically jsp:attribute defines dynamically defined XML element's attribute jsp:body Used within standard or custom tags to supply the tag body. jsp:param Adds parameters to the request object. jsp:text Used to write template text in JSP pages and documents. Usage : <jsp:text>Template data</jsp:text>
  • 32. <jsp:forward> Action <jsp:forward> is used for redirecting the request. When this action is encountered on a JSP page the control gets transferred to the page mentioned in this action. Syntax of <jsp:forward> : <jsp:forward page="URL of the another static, JSP OR Servlet page" /> Example: first.jsp <html> <head> <title>Demo of JSP Forward Action Tag</title> </head> <body> <h3>JSP page: Demo forward</h3> <jsp:forward page="second.jsp" /> </body> </html> Now when JSP engine would execute first.jsp (the above code) then after action tag, the request would be transferred to another JSP page (second.jsp). Note: first.jsp and second.jsp should be in the same directory otherwise you have to specify the complete path of second.jsp.
  • 33. <jsp:param> Action This action is useful for passing the parameters to Other JSP action tags such as JSP include & JSP forward tag. This way new JSP pages can have access to those parameters using request object itself. Syntax of <jsp:param>: <jsp: param name="param_name_here" value="value_of_parameter_here" first.jsp <html> <head> <title>Demo of JSP Param Action Tag</title> </head> <body> <h3>JSP page: Demo Param along with forward</h3> <jsp:forward page="second.jsp"> <jsp:param name ="date" value="20-05-2012" /> <jsp:param name ="time" value="10:15AM" /> <jsp:param name ="data" value="ABC" /> </jsp:forward> </body> </html> In the above example first.jsp is passing three parameters (data, time & data) to second.jsp and second.jsp can access these parameters using the below code – Date:<%= request.getParameter("date") %> Time:<%= request.getParameter("time") %> My Data:<%= request.getParameter("data") %>
  • 34. <jsp:include> Action <jsp:include> vs include directive : In <jsp:include> the file is being included during request processing while in case of include directive it has been included at translation phase. Syntax of <jsp:include> : <jsp:include page="page URL" flush="Boolean Value" /> Here page URL is: the location of the page needs to be included & flush value can be either true or false (Boolean value). Example: <html> <head> <title>Demo of JSP include Action Tag</title> </head> <body> <h3>JSP page: Demo Include</h3> <jsp:include page="sample.jsp" flush="false" /> </body> </html>
  • 35. Java Bean • A Java Bean is a java class that should follow following conventions: • It should have a no-arg constructor. • It should be Serializable. • It should provide methods to set and get the values of the properties, known as getter and setter methods. • Why use Java Bean? • According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object, so we can access this object from multiple places. Moreover, it provides the easy maintenance.
  • 36. Simple example of java bean class //Employee.java package mypack; public class Employee implements java.io.Serializable { private int id; private String name; public Employee() { } public void setId(int id) {this.id=id;} public int getId() {return id;} public void setName(String name){this.name=name;} public String getName(){return name;} }
  • 38. • Establishing JDBC connections is resource-expensive, especially when the JDBC API is used in a middle-tier server environment, such as when DataDirect Connect for JDBC or DataDirect SequeLink for JDBC is running on a Java-enabled web server. In this type of environment, performance can be improved significantly when connection pooling is used. Connection pooling means that connections are reused rather than created each time a connection is requested. To facilitate connection reuse, a memory cache of database connections, called a connection pool, is maintained by a connection pooling module as a layer on top of any standard JDBC driver product. • Connection pooling is performed in the background and does not affect how an application is coded; however, the application must use a DataSource object (an object implementing the DataSource interface) to obtain a connection instead of using the DriverManager class. A class implementing the DataSource interface may or may not provide connection pooling. A DataSource object registers with a JNDI naming service. Once a DataSource object is registered, the application retrieves it from the JNDI naming service in the standard way.
  • 39. For example: Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/SequeLink"); If the DataSource object provides connection pooling, the lookup returns a connection from the pool if one is available. If the DataSource object does not provide connection pooling or if there are no available connections in the pool, the lookup creates a new connection. The application benefits from connection reuse without requiring any code changes. Reused connections from the pool behave the same way as newly created physical connections. The application makes a connection to the database and data access works in the usual way. When the application has finished its work with the connection, the application explicitly closes the connection. For example: Connection con = ds.getConnection("scott", "tiger"); // Do some database activities using the connection... con.close(); The closing event on a pooled connection signals the pooling module to place the connection back in the connection pool for future reuse.