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

More Related Content

What's hot

Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
Kasun Madusanke
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
Peter R. Egli
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
Nuha Noor
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
Servlets
ServletsServlets
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Bootstrap
BootstrapBootstrap
Bootstrap
Jadson Santos
 
Asp.net mvc 5 ppt
Asp.net mvc 5 pptAsp.net mvc 5 ppt
Asp.net mvc 5 ppt
JavedAnsari65
 
Web services
Web servicesWeb services
Web services
Akshay Ballarpure
 
Java rmi
Java rmiJava rmi
Java rmi
kamal kotecha
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
Jalpesh Vasa
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)
Sonali Parab
 
Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5
Pallepati Vasavi
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
Amit Baghel
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 

What's hot (20)

Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Servlets
ServletsServlets
Servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Asp.net mvc 5 ppt
Asp.net mvc 5 pptAsp.net mvc 5 ppt
Asp.net mvc 5 ppt
 
Web services
Web servicesWeb services
Web services
 
Java rmi
Java rmiJava rmi
Java rmi
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)
 
Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5Mobile Application Devlopement-Database connections-UNIT-5
Mobile Application Devlopement-Database connections-UNIT-5
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 

Similar to JSP Technology I

Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
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
 
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 overview
JSP overviewJSP overview
JSP overview
Amisha Narsingani
 
Jsp
JspJsp
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
APSMIND TECHNOLOGY PVT LTD.
 
Jsp
JspJsp
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
 
Jsp interview questions by java training center
Jsp interview questions by java training centerJsp interview questions by java training center
Jsp interview questions by java training centerMaheshit Jtc
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
NishaRohit6
 

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
 
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
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
 
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
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
JSP overview
JSP overviewJSP overview
JSP overview
 
Jsp
JspJsp
Jsp
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Jsp
JspJsp
Jsp
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
 
Jsp interview questions by java training center
Jsp interview questions by java training centerJsp interview questions by java training center
Jsp interview questions by java training center
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 

More from 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
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
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
 

More from People Strategists (20)

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

Recently uploaded

"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 

Recently uploaded (20)

"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 

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