SlideShare a Scribd company logo
© People Strategists www.peoplestrategists.com Slide 1 of 76
JSP Technology -I
© People Strategists www.peoplestrategists.com Slide 2 of 76
In this session, you will learn to:
Understand JSP technology
Components of JSP
Using JavaBeans in JSP
Programming in JSP
Objectives
© People Strategists www.peoplestrategists.com Slide 3 of 76
Understanding JSP
What is JSP?
© People Strategists www.peoplestrategists.com Slide 4 of 76
Java Server Pages (JSP):
Is the Java based Web technology that enables the development of dynamic
Web sites.
Was developed by Sun Microsystems to allow server side development.
Facilitates the segregation of the work profiles of a Web designer and a Web
developer.
Allows Web designers to design and formulate the layout for a Web page by
using HTML.
Allows Web developers to work independently and use Java code and other
JSP specific tags to code the business logic.
Files are HTML files with special Tags containing Java source code that
provide the dynamic content.
Pages are saved with .jsp extension.
Source code runs on the Web server in the JSP Servlet Engine.
Understanding JSP (Contd.)
© People Strategists www.peoplestrategists.com Slide 5 of 76
How JSP is
different from Java
servlet?
Servlet vs JSP
© People Strategists www.peoplestrategists.com Slide 6 of 76
Servlet vs JSP (Contd.)
The following figure depicts the differences between the servlet and
JSP
Servlet JSP
Servlets run faster as compared to
JSP.
Servlets tie up files to independently
handle the static presentation logic
and the dynamic business logic.
Servlet programming involves
extensive coding. Any changes made
to the code requires identification of
the static code content and dynamic
code content to facilitate
incorporation of the changes.
In MVC architecture servlets act as a
controller.
Coding in servlets is hard and tedious.
JSP runs slower as compared to
servlets as it takes compilation time
to convert into Java Servlets.
JSP allows Java to be embedded
directly into an HTML page by using
special tags.
A JSP page, by virtue of the separate
placement of the static and dynamic
content, facilitates both Web
developers and the Web designer to
work independently.
In MVC architecture JSP act as a
view.
It’s easier to code in JSP than in
servlets.
© People Strategists www.peoplestrategists.com Slide 7 of 76
A JSP container (engine) works with the Web server to provide the
runtime environment and other services a JSP needs.
The following figure depicts the position of JSP container and JSP files in
a Web Application.
Identifying JSP Architecture
© People Strategists www.peoplestrategists.com Slide 8 of 76
Identifying JSP Processing
The following steps illustrates how the Web server creates the Web
page using JSP:
1. As with a normal page, your browser sends an HTTP request to the Web
server.
2. The Web server recognizes that the file required is special (.jsp), therefore
passes the JSP file to the JSP Servlet Engine.
3. If the JSP file has been called the first time, the JSP file is parsed.
4. The next step is to generate a special servlet from the JSP file. All the
HTML required is converted to println statements.
5. The servlet source code is compiled into a class.
6. The servlet is instantiated, calling the init and service methods.
7. HTML from the servlet output is sent via the Internet.
8. HTML results are displayed on the user's web browser.
© People Strategists www.peoplestrategists.com Slide 9 of 76
Identifying JSP Life Cycle
The following figure depicts the JSP life cycle.
© People Strategists www.peoplestrategists.com Slide 10 of 76
Identifying JSP Life Cycle (Contd.)
The lifecycle of a JSP page is managed using the following lifecycle
methods of the javax.servlet.jsp.JspPage interface:
jspInit(): This method initializes the servlet and is invoked when the
corresponding servlet of the requested JSP page is loaded in the Web
container for the first time.
_jspService(): This method is invoked when the servlet corresponding
to the requested JSP page is initialized and is ready to process the client
requests. The Web container invokes this method to execute the initialized
servlet to process the JSP page request.
jspDestroy(): This method is invoked by the Web container when the
corresponding servlet of the JSP page is not required to service any
subsequent requests and needs to be removed from the Web container’s
memory.
© People Strategists www.peoplestrategists.com Slide 11 of 76
Identifying the Advantages of JSP
JSP have the following advantages:
JSP are translated and compiled into JAVA servlets but are easier to
develop than JAVA servlets.
JSP have all advantages of Java i.e. write once run anywhere.
It uses simplified scripting language based syntax for embedding HTML
into JSP.
JSP containers provide easy way for accessing standard objects and
actions.
JSP reaps all the benefits provided by JAVA servlets and web container
environment, but they have an added advantage of being simpler and
more natural program for web enabling enterprise developer.
JSP use HTTP as default request /response communication paradigm and
thus make JSP ideal as Web Enabling Technology.
© People Strategists www.peoplestrategists.com Slide 12 of 76
Identifying the Limitation of JSP
JSP have the following limitations:
As JSP pages are translated to servlets and compiled, it is difficult to trace
errors occurred in JSP pages.
It require double the disk space to hold the JSP page.
It require more time when accessed for the first time as they are to be
compiled on the server.
© People Strategists www.peoplestrategists.com Slide 13 of 76
The following code shows the sample structure of a JSP page:
Identifying Simple JSP Page
<HTML>
<HEAD><TITLE>Simple JSP example></TITLE></HEAD>
<BODY>
<H1>This is a code within the JSP tags </H1>
<%-- This JSP page displays the server time--%>
<H2> Current time:
<%= new java.util.Date().getHours() %>:
<%= new java.util.Date().getMinutes()%>:
<%= new java.util.Date().getSeconds() %>
</H2>
</BODY>
</HTML>
© People Strategists www.peoplestrategists.com Slide 14 of 76
Activity: Creating a Simple JSP Page
Consider a scenario where you have been asked to create a simple JSP
page that displays the current time of the Web server. The Web page
should display output as shown in the following figure.
The Expected Output
© People Strategists www.peoplestrategists.com Slide 15 of 76
A JSP page consists of the following components:
JSP comments
JSP directives
JSP declarations
JSP scriptlets
JSP expression
JSP actions
JSP implicit objects
Identifying the Components of a JSP Page
© People Strategists www.peoplestrategists.com Slide 16 of 76
JSP comments:
are used to explain the JSP code written in a JSP page.
are not included in the HTTP response.
can be added in a JSP page by using any of the following code snippets:
<%-- comments --%>
<% /** this is a comment ... **/ %>
<!-- comments ... -->
JSP directives:
provide global information about a particular JSP page.
are of the following types:
 page directive
 include directive
 taglib directive
The syntax for defining a directive is:
 <%@ directive attribute=”value” %>;
Identifying the Components of a JSP Page (Contd.)
© People Strategists www.peoplestrategists.com Slide 17 of 76
The page directive:
is used to define the attributes that notify the Web container about the
general settings of a JSP page.
The syntax of the page directive is:
<%@ page attribute_list %>;
The following table describes the attributes supported by the page
directive:
Identifying the Components of a JSP Page (Contd.)
Attribute
Name
Description
language Defines the scripting language of the JSP page.
extends Defines the extended parent class of the JSP generated servlet.
import Imports the list of packages, classes, or interfaces into the
generated servlet.
session Specifies if the generated servlet can access the session or not. An
implicit object, session, is generated if the value is set to true.
The default value of session attribute is true.
isThreadSafe Specifies whether a JSP page is thread-safe or not.
© People Strategists www.peoplestrategists.com Slide 18 of 76
Identifying the Components of a JSP Page (Contd.)
Attribute Name Description
buffer Specifies the size of the out buffer. If size is set to none, no
buffering is performed. The default value of buffer size is 8 KB.
autoFlush Specifies that the out buffer be flushed automatically if the
value is set to true. If the value is set to false, an exception is
raised when the buffer is full. The default value of autoFlush
attribute is true.
errorPage Specifies that any un-handled exception generated will be
directed to the URL.
isErrorPage Specifies that the current JSP page is an error page, if the
attribute value is set to true. The default value of isErrorPage
attribute is false.
contentType Defines the MIME type for a response. The default value of the
contentType attribute is text/html.
© People Strategists www.peoplestrategists.com Slide 19 of 76
The taglib directive:
Imports a custom tag into the current JSP page.
Associates itself with a URI to uniquely identify a custom tag.
Associates a tag prefix string that distinguishes a custom tag with the other
tag library used in a JSP page.
Is added in a JSP page using the following code snippet:
<%@ taglib uri=“tag_lib_URI” prefix=“prefix” %>
The following table describes the attributes supported by the page
directive:
Identifying the Components of a JSP Page (Contd.)
Attribute Name Description
uri Locates the TLD file of a custom tag.
prefix Defines a prefix string to be used for distinguishing a custom
tag instance.
© People Strategists www.peoplestrategists.com Slide 20 of 76
The include directive:
Specifies the names of the files to be inserted during the compilation of the
JSP page.
Creates the contents of the included files as part of the JSP page.
Inserts a part of the code that is common to multiple pages.
The syntax of the include directive is:
<%@ include file = ”URLname” %>
Identifying the Components of a JSP Page (Contd.)
© People Strategists www.peoplestrategists.com Slide 21 of 76
JSP scripting elements:
Embed Java code directly into an HTML page.
Include various scripting elements, which are:
 Declarations:
 Provide a mechanism to define variables and methods. Declarative statements
are placed within <%! and %> symbols and always end with a semicolon.
 The following code snippet uses JSP declarations to define variables and
methods:
Identifying the Components of a JSP Page (Contd.)
<%!
int a=10;
int add() {
a=a+5;
return a;
}
%>
© People Strategists www.peoplestrategists.com Slide 22 of 76
 Expressions:
 used to directly insert values into the response output.
 evaluated when a user makes an HTTP request.
 added in a JSP page using the following code snippet:
<%= expression%>
 The following code snippet uses JSP expressions to evaluate the value of an
expression:
Identifying the Components of a JSP Page (Contd.)
<h1>The product of 5 and 2 is: <%= (2 * 5) %></h1>
© People Strategists www.peoplestrategists.com Slide 23 of 76
 Scriptlets:
 Consists of valid Java code snippets that are enclosed within <% and %>
symbols. The syntax to declare JSP scriptlets to include valid Java code is:
<% Java code %>
 The following code snippet uses JSP scriptlets to include Java code in a JSP page:
Identifying the Components of a JSP Page (Contd.)
<% int i=10;
if(i>0)
{
out.println("i is a positive number");
}
else
{
out.println("i is a negative number");
}
%>
© People Strategists www.peoplestrategists.com Slide 24 of 76
Activity: Creating a JSP Page, Using Scripting Elements and Page Directives
Consider a scenario where you have been asked to create a JSP page
that should be based on the following guidelines.
Import java.util package in a JSP page using the import attribute of the
page directive.
Set Java as the programming language for a JSP page.
Current date and time of the Web server should be displayed using JSP
expression.
Create the getSum function in the declarative section that contains two
parameters.
The Web page should display output as shown in the following figure.
The Expected Output
© People Strategists www.peoplestrategists.com Slide 25 of 76
JSP actions:
Perform tasks, such as insertion of files, reusing beans, forwarding a user to
another page, and instantiating objects.
The syntax to use a JSP action in a JSP page is:
<jsp:attribute>
The following table describes various JSP action tags:
JSP Action Description Attribute Description
<jsp:useBean> Invokes and
searches for an
existing bean.
id Uniquely identifies the instance of the bean.
class Identifies the class from which the bean
objects are to be implemented.
scope Defines the scope of the bean, such as
application, session, page, and request.
beanName Defines the referential name for the bean.
Identifying the Components of a JSP Page (Contd.)
© People Strategists www.peoplestrategists.com Slide 26 of 76
JSP Action Description Attribute Description
<jsp:forward> Used to forward
a request to a
target page.
page Specifies the URL of the target page.
<jsp:include> Includes a file in
the current JSP
page.
page Specifies the URL of the resource to be
included.
flush Specifies whether the buffer should be
flushed or not. The flush value can be
either true or false.
<jsp:getProperty> Retrieves the
property of a
bean.
name Defines the name for the bean.
property Defines the property from which the values
are to be retrieved.
<jsp:param> Defines a
parameter to be
passed to an
included or
forwarded page.
name Defines the name of the reference
parameter.
value Defines the value of the specified
parameter.
Identifying the Components of a JSP Page (Contd.)
© People Strategists www.peoplestrategists.com Slide 27 of 76
JSP Action Description Attribute Description
<jsp:setProperty> Used to set the
property of a
bean
name Specifies a name for the bean.
property Defines the property for which values are
to be set.
value Defines an explicit value for the bean
property.
param Defines the name of the request
parameter to be used.
<jsp:plugin> Executes a Java
applets or a
JavaBean.
type Defines the type of plug-in to be
included.
code Defines the name of the class to be
executed by the plug-in.
codebase Defines the path of the code.
Identifying the Components of a JSP Page (Contd.)
© People Strategists www.peoplestrategists.com Slide 28 of 76
Identifying the Components of a JSP Page (Contd.)
The following code illustrates how to use <jsp:useBean> action:
Message.java
package bean;
import java.io.Serializable;
public class Message implements
Serializable {
private String message = "Hello from
JSP!";
public String getMessage()
{
return message;
}
public void setMessage(String m)
{
message = m;
}
public Message() {
}
}
<HTML>
<HEAD>
<TITLE>Bean Demo</TITLE>
</HEAD>
<BODY>
<H1>Setting a Property Value</H1>
<jsp:useBean id="bean1"
class="bean.Message" />
The message is: <jsp:getProperty
name="bean1" property="message" />
<BR>
<jsp:setProperty name="bean1"
property="message" value="Hello
again!" />
Now the message is: <jsp:getProperty
name="bean1" property="message" />
</BODY>
</HTML>
BeanDemo.jsp
© People Strategists www.peoplestrategists.com Slide 29 of 76
Identifying the Components of a JSP Page (Contd.)
The following code illustrates how to use <jsp:include> action:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
First.jsp
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page=“First.jsp" flush="true" />
</center>
</body>
</html>
Myfile.jsp
© People Strategists www.peoplestrategists.com Slide 30 of 76
JSP implicit objects:
are predefined objects provided by the container that can be included in JSP
expressions and scriptlets.
are mapped to the classes and interfaces of the servlet API.
The following table describes various JSP implicit objects:
Implicit Object Class Description
application javax.servlet.
ServletContext
The application object defines a Web
application. Usually, it is the application
in the current Web context.
config javax.Servlet.
ServletConfig
Represents the object of a
ServletConfig class.
exception java.lang.Throwable Represents the Throwable exception,
in a JSP page.
request javax.servlet.http.H
ttpServletRequest
Represents a request object of
HttpServletRequest. It is used
to retrieve data submitted along
with a request.
Identifying the Components of a JSP Page (Contd.)
© People Strategists www.peoplestrategists.com Slide 31 of 76
Implicit Object Class Description
out javax.servlet.jsp.
JspWriter
Represents an object of JspWriter to
send response to the client.
JspWriter extends the PrintWriter
class and is used by JSP pages to
send client responses.
page java.lang.Object Represents the current instance of
the JSP page that in turn is used to
refer to the current instance of the
generated servlet.
session javax.servlet.http.
HttpSession
Represents a session object of the
HttpSession interface.
response javax.servlet.http.Http
ServletResponse
Represents a response object of
HttpServletResponse that is used to
send an HTML output to the client.
pageContext javax.servlet.jsp.
PageContext
Represents a page context for a JSP
page.
Identifying the Components of a JSP Page (Contd.)
© People Strategists www.peoplestrategists.com Slide 32 of 76
Identifying the Components of a JSP Page (Contd.)
The following code illustrates how to use exception object:
<%@ page language="java"
contentType="text/html"
isErrorPage="true" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
The exception which occurred
during the processing is :- <br>
<span style="color:red">
<%=exception.toString() %>
</span>
</body>
</html>
Error_page.jsp
<%@ page language="java"
contentType="text/html"
errorPage=“Error_page.jsp“ %>
<html>
<head>
<title>Exception</title>
</head>
<body>
<%
String str=null;
str.charAt(0);
%>
</body>
</html>
Error_demo.jsp
© People Strategists www.peoplestrategists.com Slide 33 of 76
Identifying the Components of a JSP Page (Contd.)
The following code illustrates how to use session object to get
details of the user session :
Session_demo.jsp
<%@page import = "java.util.*" session="true"%>
<HTML>
<HEAD><TITLE>Using Sessions to Track Users</TITLE></HEAD>
<BODY>
<%
Integer counter = (Integer)session.getAttribute("counter");
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}
session.setAttribute("counter", counter);
%>
<H1>Using Sessions to Track Users</H1>
Session ID:<span
style="color:red"><%=session.getId()%></span><BR>
Session creation time:<span style="color:red"><%=new
Date(session.getCreationTime())%></span> <BR>
Last accessed time: <span style="color:red"><%=new
Date(session.getLastAccessedTime())%></span> <BR>
Number of times you have been here: <big> <%=counter%> </big>
</BODY> </HTML>
© People Strategists www.peoplestrategists.com Slide 34 of 76
Activity: Creating a Login Page to Validates Users Credential
Consider a scenario where you have been asked to create a JSP page
that validates the users credentials and should be based on the
following guidelines:
Check whether the entered used name is equal to Peter and password is
equal to Parker.
Welcome message should be display to the valid user and alert box should
be displayed to the invalid user.
JSP built-in object should be used to handle the client request, response,
and session.
The Web page should display output as shown in the following figures.
© People Strategists www.peoplestrategists.com Slide 35 of 76
Activity: Working with JSP:UseBean
Consider a scenario where you have been asked to create a JSP page
that returns the cube, square, and square root values of the entered
values. The JSP page should be based on the following guidelines:
Create a Java bean class to perform mathematical operations.
Set the scope of the JSP:UseBean to session.
The Web page should display output as shown in the following figures.
© People Strategists www.peoplestrategists.com Slide 36 of 76
JSP API includes the following classes:
The ErrorData class
The JSPWriter class
The PageContext class
Programming in JSP
© People Strategists www.peoplestrategists.com Slide 37 of 76
The ErrorData class:
Defines error information for error pages.
Sets the value of the page directive, isErrorPage to true, to indicate that a
page is an error page.
Contains various methods, which are:
 getRequestURL(): Returns the requested URL in the form of a
string.
 setServletName(): Returns the name of the servlet invoked in the
form of a string.
 getStatusCode(): Returns the status code of the error in the form
of an integer.
 getThrowable(): Returns the Throwable exception that caused the
error.
Programming in JSP (Contd.)
© People Strategists www.peoplestrategists.com Slide 38 of 76
The JspWriter class:
Writes action and template data in a JSP page.
Refers the object of JspWriter class by the implicit variable, out.
Contains various methods, which are:
 clear()
 close()
 flush()
 getBufferSize()
 print()
 println()
Programming in JSP (Contd.)
© People Strategists www.peoplestrategists.com Slide 39 of 76
The PageContext class:
Provides context information when JSP is used in the servlet environment.
Contains various methods, which are:
 forward()
 getPage()
 getRequest()
 getResponse()
 getServletConfig()
 getServletContext()
 getSession()
 include()
Programming in JSP (Contd.)
© People Strategists www.peoplestrategists.com Slide 40 of 76
Problem statement:
James needs to create an application that validates the customer id and
password of every customer before they can access their account details.
The customer id has to be in a numeric form. He also wants that an error
message should be displayed to the customer, if the entered customer id or
password is incorrect. Before the changes can be made to the entire
application, James wants to test this functionality by making a sample
application for a specific customer. The Web page should display output as
shown in the following figure.
Activity: Programming in JSP
© People Strategists www.peoplestrategists.com Slide 41 of 76
Java Server Pages (JSP) is the Java based Web technology that enables
the development of dynamic Web sites.
JSP allows Web developers to work independently and use Java code and
other JSP specific tags to code the business logic.
A JSP container (engine) works with the Web server to provide the
runtime environment and other services a JSP needs.
The jspInit()method initializes the servlet and is invoked when the
corresponding servlet of the requested JSP page is loaded in the Web
container for the first time.
The _jspService()method is invoked when the servlet corresponding
to the requested JSP page is initialized and is ready to process the client
requests.
JSP directives provide global information about a particular JSP page.
The page directive is used to define the attributes that notify the Web
container about the general settings of a JSP page.
Summary
© People Strategists www.peoplestrategists.com Slide 42 of 76
The taglib directive imports a custom tag into the current JSP page.
The include directive specifies the names of the files to be inserted
during the compilation of the JSP page.
JSP scripting elements embed Java code directly into an HTML page.
JSP actions perform tasks, such as insertion of files, reusing beans,
forwarding a user to another page, and instantiating objects.
JSP implicit objects are predefined objects provided by the container that
can be included in JSP expressions and scriptlets.
The ErrorData class defines error information for error pages.
The JspWriter class writes action and template data in a JSP page.
The PageContext class provides context information when JSP is used
in the servlet environment.
Summary (Contd.)
Ad

More Related Content

What's hot (20)

Swing
SwingSwing
Swing
Jaydeep Viradiya
 
Java OOP Concept
Java OOP ConceptJava OOP Concept
Java OOP Concept
NikitaGour5
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web Services
IMC Institute
 
Java collection
Java collectionJava collection
Java collection
Arati Gadgil
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
Vipin Yadav
 
Java servlets
Java servletsJava servlets
Java servlets
yuvarani p
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Java swing
Java swingJava swing
Java swing
Apurbo Datta
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Java J2EE
Java J2EEJava J2EE
Java J2EE
Sandeep Rawat
 
This keyword and final keyword
This keyword and final  keywordThis keyword and final  keyword
This keyword and final keyword
kinjalbirare
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Java OOP Concept
Java OOP ConceptJava OOP Concept
Java OOP Concept
NikitaGour5
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Java Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web ServicesJava Web Services [1/5]: Introduction to Web Services
Java Web Services [1/5]: Introduction to Web Services
IMC Institute
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
Vipin Yadav
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
This keyword and final keyword
This keyword and final  keywordThis keyword and final  keyword
This keyword and final keyword
kinjalbirare
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 

Similar to JSP Technology I (20)

Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
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
 
Module 3.pptx.............................
Module 3.pptx.............................Module 3.pptx.............................
Module 3.pptx.............................
Betty333100
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
Atul Giri
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
Yoga Raja
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
Arumugam90
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
Kalpana T
 
Jsp
JspJsp
Jsp
Rahul Goyal
 
Jsp
JspJsp
Jsp
Rahul Goyal
 
JSP overview
JSP overviewJSP overview
JSP overview
Amisha Narsingani
 
Jsp
JspJsp
Jsp
Maheshit Jtc
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
APSMIND TECHNOLOGY PVT LTD.
 
Java server pages
Java server pagesJava server pages
Java server pages
Abhishek Kesharwani
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
Jsp
JspJsp
Jsp
Pooja Verma
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
Biswabrata Banerjee
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
Vipin Yadav
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
ManishaPatil932723
 
Ad

More from People Strategists (20)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
People Strategists
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
People Strategists
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
People Strategists
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
People Strategists
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
People Strategists
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
People Strategists
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
People Strategists
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
People Strategists
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
People Strategists
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
People Strategists
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
People Strategists
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
People Strategists
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
People Strategists
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
People Strategists
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
People Strategists
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
People Strategists
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
People Strategists
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
People Strategists
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
People Strategists
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
People Strategists
 
Ad

Recently uploaded (20)

#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
 

JSP Technology I

  • 1. © People Strategists www.peoplestrategists.com Slide 1 of 76 JSP Technology -I
  • 2. © People Strategists www.peoplestrategists.com Slide 2 of 76 In this session, you will learn to: Understand JSP technology Components of JSP Using JavaBeans in JSP Programming in JSP Objectives
  • 3. © People Strategists www.peoplestrategists.com Slide 3 of 76 Understanding JSP What is JSP?
  • 4. © People Strategists www.peoplestrategists.com Slide 4 of 76 Java Server Pages (JSP): Is the Java based Web technology that enables the development of dynamic Web sites. Was developed by Sun Microsystems to allow server side development. Facilitates the segregation of the work profiles of a Web designer and a Web developer. Allows Web designers to design and formulate the layout for a Web page by using HTML. Allows Web developers to work independently and use Java code and other JSP specific tags to code the business logic. Files are HTML files with special Tags containing Java source code that provide the dynamic content. Pages are saved with .jsp extension. Source code runs on the Web server in the JSP Servlet Engine. Understanding JSP (Contd.)
  • 5. © People Strategists www.peoplestrategists.com Slide 5 of 76 How JSP is different from Java servlet? Servlet vs JSP
  • 6. © People Strategists www.peoplestrategists.com Slide 6 of 76 Servlet vs JSP (Contd.) The following figure depicts the differences between the servlet and JSP Servlet JSP Servlets run faster as compared to JSP. Servlets tie up files to independently handle the static presentation logic and the dynamic business logic. Servlet programming involves extensive coding. Any changes made to the code requires identification of the static code content and dynamic code content to facilitate incorporation of the changes. In MVC architecture servlets act as a controller. Coding in servlets is hard and tedious. JSP runs slower as compared to servlets as it takes compilation time to convert into Java Servlets. JSP allows Java to be embedded directly into an HTML page by using special tags. A JSP page, by virtue of the separate placement of the static and dynamic content, facilitates both Web developers and the Web designer to work independently. In MVC architecture JSP act as a view. It’s easier to code in JSP than in servlets.
  • 7. © People Strategists www.peoplestrategists.com Slide 7 of 76 A JSP container (engine) works with the Web server to provide the runtime environment and other services a JSP needs. The following figure depicts the position of JSP container and JSP files in a Web Application. Identifying JSP Architecture
  • 8. © People Strategists www.peoplestrategists.com Slide 8 of 76 Identifying JSP Processing The following steps illustrates how the Web server creates the Web page using JSP: 1. As with a normal page, your browser sends an HTTP request to the Web server. 2. The Web server recognizes that the file required is special (.jsp), therefore passes the JSP file to the JSP Servlet Engine. 3. If the JSP file has been called the first time, the JSP file is parsed. 4. The next step is to generate a special servlet from the JSP file. All the HTML required is converted to println statements. 5. The servlet source code is compiled into a class. 6. The servlet is instantiated, calling the init and service methods. 7. HTML from the servlet output is sent via the Internet. 8. HTML results are displayed on the user's web browser.
  • 9. © People Strategists www.peoplestrategists.com Slide 9 of 76 Identifying JSP Life Cycle The following figure depicts the JSP life cycle.
  • 10. © People Strategists www.peoplestrategists.com Slide 10 of 76 Identifying JSP Life Cycle (Contd.) The lifecycle of a JSP page is managed using the following lifecycle methods of the javax.servlet.jsp.JspPage interface: jspInit(): This method initializes the servlet and is invoked when the corresponding servlet of the requested JSP page is loaded in the Web container for the first time. _jspService(): This method is invoked when the servlet corresponding to the requested JSP page is initialized and is ready to process the client requests. The Web container invokes this method to execute the initialized servlet to process the JSP page request. jspDestroy(): This method is invoked by the Web container when the corresponding servlet of the JSP page is not required to service any subsequent requests and needs to be removed from the Web container’s memory.
  • 11. © People Strategists www.peoplestrategists.com Slide 11 of 76 Identifying the Advantages of JSP JSP have the following advantages: JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA servlets. JSP have all advantages of Java i.e. write once run anywhere. It uses simplified scripting language based syntax for embedding HTML into JSP. JSP containers provide easy way for accessing standard objects and actions. JSP reaps all the benefits provided by JAVA servlets and web container environment, but they have an added advantage of being simpler and more natural program for web enabling enterprise developer. JSP use HTTP as default request /response communication paradigm and thus make JSP ideal as Web Enabling Technology.
  • 12. © People Strategists www.peoplestrategists.com Slide 12 of 76 Identifying the Limitation of JSP JSP have the following limitations: As JSP pages are translated to servlets and compiled, it is difficult to trace errors occurred in JSP pages. It require double the disk space to hold the JSP page. It require more time when accessed for the first time as they are to be compiled on the server.
  • 13. © People Strategists www.peoplestrategists.com Slide 13 of 76 The following code shows the sample structure of a JSP page: Identifying Simple JSP Page <HTML> <HEAD><TITLE>Simple JSP example></TITLE></HEAD> <BODY> <H1>This is a code within the JSP tags </H1> <%-- This JSP page displays the server time--%> <H2> Current time: <%= new java.util.Date().getHours() %>: <%= new java.util.Date().getMinutes()%>: <%= new java.util.Date().getSeconds() %> </H2> </BODY> </HTML>
  • 14. © People Strategists www.peoplestrategists.com Slide 14 of 76 Activity: Creating a Simple JSP Page Consider a scenario where you have been asked to create a simple JSP page that displays the current time of the Web server. The Web page should display output as shown in the following figure. The Expected Output
  • 15. © People Strategists www.peoplestrategists.com Slide 15 of 76 A JSP page consists of the following components: JSP comments JSP directives JSP declarations JSP scriptlets JSP expression JSP actions JSP implicit objects Identifying the Components of a JSP Page
  • 16. © People Strategists www.peoplestrategists.com Slide 16 of 76 JSP comments: are used to explain the JSP code written in a JSP page. are not included in the HTTP response. can be added in a JSP page by using any of the following code snippets: <%-- comments --%> <% /** this is a comment ... **/ %> <!-- comments ... --> JSP directives: provide global information about a particular JSP page. are of the following types:  page directive  include directive  taglib directive The syntax for defining a directive is:  <%@ directive attribute=”value” %>; Identifying the Components of a JSP Page (Contd.)
  • 17. © People Strategists www.peoplestrategists.com Slide 17 of 76 The page directive: is used to define the attributes that notify the Web container about the general settings of a JSP page. The syntax of the page directive is: <%@ page attribute_list %>; The following table describes the attributes supported by the page directive: Identifying the Components of a JSP Page (Contd.) Attribute Name Description language Defines the scripting language of the JSP page. extends Defines the extended parent class of the JSP generated servlet. import Imports the list of packages, classes, or interfaces into the generated servlet. session Specifies if the generated servlet can access the session or not. An implicit object, session, is generated if the value is set to true. The default value of session attribute is true. isThreadSafe Specifies whether a JSP page is thread-safe or not.
  • 18. © People Strategists www.peoplestrategists.com Slide 18 of 76 Identifying the Components of a JSP Page (Contd.) Attribute Name Description buffer Specifies the size of the out buffer. If size is set to none, no buffering is performed. The default value of buffer size is 8 KB. autoFlush Specifies that the out buffer be flushed automatically if the value is set to true. If the value is set to false, an exception is raised when the buffer is full. The default value of autoFlush attribute is true. errorPage Specifies that any un-handled exception generated will be directed to the URL. isErrorPage Specifies that the current JSP page is an error page, if the attribute value is set to true. The default value of isErrorPage attribute is false. contentType Defines the MIME type for a response. The default value of the contentType attribute is text/html.
  • 19. © People Strategists www.peoplestrategists.com Slide 19 of 76 The taglib directive: Imports a custom tag into the current JSP page. Associates itself with a URI to uniquely identify a custom tag. Associates a tag prefix string that distinguishes a custom tag with the other tag library used in a JSP page. Is added in a JSP page using the following code snippet: <%@ taglib uri=“tag_lib_URI” prefix=“prefix” %> The following table describes the attributes supported by the page directive: Identifying the Components of a JSP Page (Contd.) Attribute Name Description uri Locates the TLD file of a custom tag. prefix Defines a prefix string to be used for distinguishing a custom tag instance.
  • 20. © People Strategists www.peoplestrategists.com Slide 20 of 76 The include directive: Specifies the names of the files to be inserted during the compilation of the JSP page. Creates the contents of the included files as part of the JSP page. Inserts a part of the code that is common to multiple pages. The syntax of the include directive is: <%@ include file = ”URLname” %> Identifying the Components of a JSP Page (Contd.)
  • 21. © People Strategists www.peoplestrategists.com Slide 21 of 76 JSP scripting elements: Embed Java code directly into an HTML page. Include various scripting elements, which are:  Declarations:  Provide a mechanism to define variables and methods. Declarative statements are placed within <%! and %> symbols and always end with a semicolon.  The following code snippet uses JSP declarations to define variables and methods: Identifying the Components of a JSP Page (Contd.) <%! int a=10; int add() { a=a+5; return a; } %>
  • 22. © People Strategists www.peoplestrategists.com Slide 22 of 76  Expressions:  used to directly insert values into the response output.  evaluated when a user makes an HTTP request.  added in a JSP page using the following code snippet: <%= expression%>  The following code snippet uses JSP expressions to evaluate the value of an expression: Identifying the Components of a JSP Page (Contd.) <h1>The product of 5 and 2 is: <%= (2 * 5) %></h1>
  • 23. © People Strategists www.peoplestrategists.com Slide 23 of 76  Scriptlets:  Consists of valid Java code snippets that are enclosed within <% and %> symbols. The syntax to declare JSP scriptlets to include valid Java code is: <% Java code %>  The following code snippet uses JSP scriptlets to include Java code in a JSP page: Identifying the Components of a JSP Page (Contd.) <% int i=10; if(i>0) { out.println("i is a positive number"); } else { out.println("i is a negative number"); } %>
  • 24. © People Strategists www.peoplestrategists.com Slide 24 of 76 Activity: Creating a JSP Page, Using Scripting Elements and Page Directives Consider a scenario where you have been asked to create a JSP page that should be based on the following guidelines. Import java.util package in a JSP page using the import attribute of the page directive. Set Java as the programming language for a JSP page. Current date and time of the Web server should be displayed using JSP expression. Create the getSum function in the declarative section that contains two parameters. The Web page should display output as shown in the following figure. The Expected Output
  • 25. © People Strategists www.peoplestrategists.com Slide 25 of 76 JSP actions: Perform tasks, such as insertion of files, reusing beans, forwarding a user to another page, and instantiating objects. The syntax to use a JSP action in a JSP page is: <jsp:attribute> The following table describes various JSP action tags: JSP Action Description Attribute Description <jsp:useBean> Invokes and searches for an existing bean. id Uniquely identifies the instance of the bean. class Identifies the class from which the bean objects are to be implemented. scope Defines the scope of the bean, such as application, session, page, and request. beanName Defines the referential name for the bean. Identifying the Components of a JSP Page (Contd.)
  • 26. © People Strategists www.peoplestrategists.com Slide 26 of 76 JSP Action Description Attribute Description <jsp:forward> Used to forward a request to a target page. page Specifies the URL of the target page. <jsp:include> Includes a file in the current JSP page. page Specifies the URL of the resource to be included. flush Specifies whether the buffer should be flushed or not. The flush value can be either true or false. <jsp:getProperty> Retrieves the property of a bean. name Defines the name for the bean. property Defines the property from which the values are to be retrieved. <jsp:param> Defines a parameter to be passed to an included or forwarded page. name Defines the name of the reference parameter. value Defines the value of the specified parameter. Identifying the Components of a JSP Page (Contd.)
  • 27. © People Strategists www.peoplestrategists.com Slide 27 of 76 JSP Action Description Attribute Description <jsp:setProperty> Used to set the property of a bean name Specifies a name for the bean. property Defines the property for which values are to be set. value Defines an explicit value for the bean property. param Defines the name of the request parameter to be used. <jsp:plugin> Executes a Java applets or a JavaBean. type Defines the type of plug-in to be included. code Defines the name of the class to be executed by the plug-in. codebase Defines the path of the code. Identifying the Components of a JSP Page (Contd.)
  • 28. © People Strategists www.peoplestrategists.com Slide 28 of 76 Identifying the Components of a JSP Page (Contd.) The following code illustrates how to use <jsp:useBean> action: Message.java package bean; import java.io.Serializable; public class Message implements Serializable { private String message = "Hello from JSP!"; public String getMessage() { return message; } public void setMessage(String m) { message = m; } public Message() { } } <HTML> <HEAD> <TITLE>Bean Demo</TITLE> </HEAD> <BODY> <H1>Setting a Property Value</H1> <jsp:useBean id="bean1" class="bean.Message" /> The message is: <jsp:getProperty name="bean1" property="message" /> <BR> <jsp:setProperty name="bean1" property="message" value="Hello again!" /> Now the message is: <jsp:getProperty name="bean1" property="message" /> </BODY> </HTML> BeanDemo.jsp
  • 29. © People Strategists www.peoplestrategists.com Slide 29 of 76 Identifying the Components of a JSP Page (Contd.) The following code illustrates how to use <jsp:include> action: <p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> First.jsp <html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:include page=“First.jsp" flush="true" /> </center> </body> </html> Myfile.jsp
  • 30. © People Strategists www.peoplestrategists.com Slide 30 of 76 JSP implicit objects: are predefined objects provided by the container that can be included in JSP expressions and scriptlets. are mapped to the classes and interfaces of the servlet API. The following table describes various JSP implicit objects: Implicit Object Class Description application javax.servlet. ServletContext The application object defines a Web application. Usually, it is the application in the current Web context. config javax.Servlet. ServletConfig Represents the object of a ServletConfig class. exception java.lang.Throwable Represents the Throwable exception, in a JSP page. request javax.servlet.http.H ttpServletRequest Represents a request object of HttpServletRequest. It is used to retrieve data submitted along with a request. Identifying the Components of a JSP Page (Contd.)
  • 31. © People Strategists www.peoplestrategists.com Slide 31 of 76 Implicit Object Class Description out javax.servlet.jsp. JspWriter Represents an object of JspWriter to send response to the client. JspWriter extends the PrintWriter class and is used by JSP pages to send client responses. page java.lang.Object Represents the current instance of the JSP page that in turn is used to refer to the current instance of the generated servlet. session javax.servlet.http. HttpSession Represents a session object of the HttpSession interface. response javax.servlet.http.Http ServletResponse Represents a response object of HttpServletResponse that is used to send an HTML output to the client. pageContext javax.servlet.jsp. PageContext Represents a page context for a JSP page. Identifying the Components of a JSP Page (Contd.)
  • 32. © People Strategists www.peoplestrategists.com Slide 32 of 76 Identifying the Components of a JSP Page (Contd.) The following code illustrates how to use exception object: <%@ page language="java" contentType="text/html" isErrorPage="true" %> <html> <head> <title>Error Page</title> </head> <body> The exception which occurred during the processing is :- <br> <span style="color:red"> <%=exception.toString() %> </span> </body> </html> Error_page.jsp <%@ page language="java" contentType="text/html" errorPage=“Error_page.jsp“ %> <html> <head> <title>Exception</title> </head> <body> <% String str=null; str.charAt(0); %> </body> </html> Error_demo.jsp
  • 33. © People Strategists www.peoplestrategists.com Slide 33 of 76 Identifying the Components of a JSP Page (Contd.) The following code illustrates how to use session object to get details of the user session : Session_demo.jsp <%@page import = "java.util.*" session="true"%> <HTML> <HEAD><TITLE>Using Sessions to Track Users</TITLE></HEAD> <BODY> <% Integer counter = (Integer)session.getAttribute("counter"); if (counter == null) { counter = new Integer(1); } else { counter = new Integer(counter.intValue() + 1); } session.setAttribute("counter", counter); %> <H1>Using Sessions to Track Users</H1> Session ID:<span style="color:red"><%=session.getId()%></span><BR> Session creation time:<span style="color:red"><%=new Date(session.getCreationTime())%></span> <BR> Last accessed time: <span style="color:red"><%=new Date(session.getLastAccessedTime())%></span> <BR> Number of times you have been here: <big> <%=counter%> </big> </BODY> </HTML>
  • 34. © People Strategists www.peoplestrategists.com Slide 34 of 76 Activity: Creating a Login Page to Validates Users Credential Consider a scenario where you have been asked to create a JSP page that validates the users credentials and should be based on the following guidelines: Check whether the entered used name is equal to Peter and password is equal to Parker. Welcome message should be display to the valid user and alert box should be displayed to the invalid user. JSP built-in object should be used to handle the client request, response, and session. The Web page should display output as shown in the following figures.
  • 35. © People Strategists www.peoplestrategists.com Slide 35 of 76 Activity: Working with JSP:UseBean Consider a scenario where you have been asked to create a JSP page that returns the cube, square, and square root values of the entered values. The JSP page should be based on the following guidelines: Create a Java bean class to perform mathematical operations. Set the scope of the JSP:UseBean to session. The Web page should display output as shown in the following figures.
  • 36. © People Strategists www.peoplestrategists.com Slide 36 of 76 JSP API includes the following classes: The ErrorData class The JSPWriter class The PageContext class Programming in JSP
  • 37. © People Strategists www.peoplestrategists.com Slide 37 of 76 The ErrorData class: Defines error information for error pages. Sets the value of the page directive, isErrorPage to true, to indicate that a page is an error page. Contains various methods, which are:  getRequestURL(): Returns the requested URL in the form of a string.  setServletName(): Returns the name of the servlet invoked in the form of a string.  getStatusCode(): Returns the status code of the error in the form of an integer.  getThrowable(): Returns the Throwable exception that caused the error. Programming in JSP (Contd.)
  • 38. © People Strategists www.peoplestrategists.com Slide 38 of 76 The JspWriter class: Writes action and template data in a JSP page. Refers the object of JspWriter class by the implicit variable, out. Contains various methods, which are:  clear()  close()  flush()  getBufferSize()  print()  println() Programming in JSP (Contd.)
  • 39. © People Strategists www.peoplestrategists.com Slide 39 of 76 The PageContext class: Provides context information when JSP is used in the servlet environment. Contains various methods, which are:  forward()  getPage()  getRequest()  getResponse()  getServletConfig()  getServletContext()  getSession()  include() Programming in JSP (Contd.)
  • 40. © People Strategists www.peoplestrategists.com Slide 40 of 76 Problem statement: James needs to create an application that validates the customer id and password of every customer before they can access their account details. The customer id has to be in a numeric form. He also wants that an error message should be displayed to the customer, if the entered customer id or password is incorrect. Before the changes can be made to the entire application, James wants to test this functionality by making a sample application for a specific customer. The Web page should display output as shown in the following figure. Activity: Programming in JSP
  • 41. © People Strategists www.peoplestrategists.com Slide 41 of 76 Java Server Pages (JSP) is the Java based Web technology that enables the development of dynamic Web sites. JSP allows Web developers to work independently and use Java code and other JSP specific tags to code the business logic. A JSP container (engine) works with the Web server to provide the runtime environment and other services a JSP needs. The jspInit()method initializes the servlet and is invoked when the corresponding servlet of the requested JSP page is loaded in the Web container for the first time. The _jspService()method is invoked when the servlet corresponding to the requested JSP page is initialized and is ready to process the client requests. JSP directives provide global information about a particular JSP page. The page directive is used to define the attributes that notify the Web container about the general settings of a JSP page. Summary
  • 42. © People Strategists www.peoplestrategists.com Slide 42 of 76 The taglib directive imports a custom tag into the current JSP page. The include directive specifies the names of the files to be inserted during the compilation of the JSP page. JSP scripting elements embed Java code directly into an HTML page. JSP actions perform tasks, such as insertion of files, reusing beans, forwarding a user to another page, and instantiating objects. JSP implicit objects are predefined objects provided by the container that can be included in JSP expressions and scriptlets. The ErrorData class defines error information for error pages. The JspWriter class writes action and template data in a JSP page. The PageContext class provides context information when JSP is used in the servlet environment. Summary (Contd.)