SlideShare a Scribd company logo
JSP
Java Server Pages
K.SASIDHAR
servlets
• Server side Java programs
• Solve scalability issue
• serlvets are run on threads of execution not
separate processes
• Solve portability issue
• runs on every platform that supports Java
• supported by all most popular web servers
• Issues:
• html tags are embedded in java programs within
out.print() statements
JSP -- Introduction
• server-side technology
• separates dynamic content from static
content of a page
– Java scriptlets embedded into html-like page
• Separates the work of
– java programmers
– page authors
Introduction
• Java Server Pages (JSP) technology provides a simplified,
fast way to create web pages that display dynamically-
generated content
• Developed by Sun Micro Systems in 1999.
• Defines interaction between the server and JSP and
describes the format and syntax of the page.
JSP page
• A page created by the web developer that includes
JSP technology-specific and custom tags, in
combination with other static (HTML or XML)
tags.
• A JSP page has the extension .jsp or .jspx;
• This signals to the web server that the JSP engine
will process elements on this page.
• Using the .xml deployment descriptor, additional
extensions can be associated with the JSP engine.
Advantages of JSP
• Provides a powerful and flexible mechanism to
produce dynamic web pages.
• It allows the creation of custom tag libraries to
meet the specific needs of the project.
• It provides built-in support of HTTP session
management.
• Can be integrated with : JDBC API, Thread API,
EJB API etc..
JSP notations
• <% … %> jsp scriplet  a fragment of code that
run when the user request the webpage.
• < %= > delimeter used for expressions
• <%@ > jsp directives
Anatomy of a jsp page
<%@page contenttype = “text/html” language = “java%”>
<%@page import = “java.util.Date” session = “false”%>
Jsp elements
<html>
<head>
<title> simple jsp page demo</title>
</head>
<body>
<h3> current time is : </h3>
Template data
<%= new Date()%> -- > jsp elements
</body>
</html> Template data
%@ is jsp directive
%= is jsp element
In a simple way
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Client and Server with JSP
Java Server Pages (JSP) in detail
Client’s
Computer
Server
1.Browser requests HTML
7. Server sends HTML
back to browser
servlet
servlet
class 5.The servlet
runs and
generates
HTML
Java Engine
6. Java Engine sends HTML to server
2. Server sends requests to Java Engine
3. If needed, the Java Engine
reads the .jsp file
4. The JSP is turned into a
servlet, compiled, and loaded
Bean
JSP Life cycle
Translation Time
• A JSP application is usually a collection of JSP
files, HTML files, graphics and other resources.
• A JSP page is compiled when your user loads it
into a Web browser
1. When the user loads the page for the first time, the files
that make up the application are all translated together,
without any dynamic data, into one Java source file (a
.java file)
2. The .java file is compiled to a .class file. In most
implementations, the .java file is a Java servlet that
complies with the Java Servlet API.
JSP Elements
• Declarations <%! code %>
<jsp:declaration>
</jsp:declaration >
• Expressions <%= expression %>
<jsp:expression>
</jsp:expression>
• Scriplets <% code %>
<jsp:scriplet>
</jsp:scriplet >
Declaration
• Declares a variable or method valid in the scripting language used in
the JSP page.
– Syntax
<%! declaration; [ declaration; ]+ ... %>
– Examples
<%! String destin; %>
<%! Public String getDestination()
{return destin;}%>
<%! Circle a = new Circle(2.0); %>
– You can declare any number of variables or methods within
one declaration
element, as long as you end each declaration with a semicolon.
– The declaration must be valid in the Java programming
language.
Declaration Example
<HTML>
<HEAD><TITLE>JSP Declarations</TITLE></HEAD>
<BODY><H1>JSP Declarations</H1>
<%! private int keepCount = 0; %>
<H2>
Page accessed:
<%= ++keepCount %>
times
</H2>
</BODY>
</HTML>
Predefined Variable – Implicit Objects
• request – Object of HttpServletRequest (request parameters,
HTTP headers, cookies
• response – Object of HttpServletResponse
• out - Object of PrintWriter buffered version JspWriter
• session - Object of HttpSession associated with the request
• application - Object of ServletContext shared by all servlets in the
engine
• config - Object of ServletConfig
• pageContext - Object of PageContext in JSP for a single point of
access
page – variable synonym for this object
Expression
• Contains an expression valid in the scripting language used in the
JSP page.
– Syntax
<%= expression %>
<%! String name = new String(“JSP World”); %>
<%! public String getName() { return name; } %>
<B><%= getName() %></B>
Description:
An expression element contains a scripting language expression
that is evaluated, converted to a String, and inserted where the
expression appears in the JSP file.
– Because the value of an expression is converted to a String, you
can use an expression within a line of text, whether or not it is
tagged with HTML, in a JSPfile. Expressions are evaluated from
left to right.
Expression Example
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
</UL>
</BODY>
</HTML>
Scriptlet
• Contains a code fragment valid in the page scripting
language.
– Syntax
<% code fragment %>
<%
String var1 =
request.getParameter("name");
out.println(var1);
%>
This code will be placed in the generated servlet method:
_jspService()
Scriplet Example
<HTML>
<HEAD><TITLE>Weather</TITLE></HEAD>
<BODY>
<H2>Today's weather</H2>
<% if (Math.random() < 0.5) { %>
Today will be a <B>suny</B> day!
<% } else { %>
Today will be a <B>windy</B> day!
<% } %>
</BODY>
</HTML>
JSP
Scriptlets
Example
<%
for (int i=100; i>=0; i--)
{
%>
<%= i %> The numbers in
decending order are: <br>
<%
}
%>
Another example: JSP Tags + HTML Tags
<h2>Table of Square Roots</h2>
<table border=2>
<tr>
<td><b>Number</b></td>
<td><b>Square Root</b></td>
</tr>
<%
for (int n=0; n<=100; n++)
{
%>
<tr>
<td><%=n%></td>
<td><%=Math.sqrt(n)%></td>
</tr>
<%
}
%>
</table>
JSP Page Directive
• Directives are messages to the JSP container and do not
produce output into the current output stream
– Syntax:
<%@ directive attribute=“value” %>
<%@ directive attribute1=“value1”
attribute1 =“value2” … %>
There are three types of directives:
1. page
2. include
3. Taglib
XML form: <jsp:directive.directiveType
attribute=“value” />
Purpose of the page Directive
• Give high-level information about the servlet that will
result from the JSP page
• Can control
– Which classes are imported
– What class the servlet extends
– What MIME type is generated
( Multipurpose Internet Mail extensions )
– How multithreading is handled
– If the servlet participates in sessions
– The size and behavior of the output buffer
– What page handles unexpected errors
Page Directive
• Defines attributes that apply to an entire JSP page.
<%@ page
[ language="java" ]
[ extends="package.class" ]
[ import="{package.class |
package.*}, ..." ]
[ session="true|false" ]
[ buffer="none|8kb|sizekb" ]
[ autoFlush="true|false" ]
[ isThreadSafe="true|false" ]
[ info="text" ]
[ errorPage="relativeURL" ]
[ contentType="mimeType [
;charset=characterSet ]"
[ isErrorPage="true|false" ]
%>
Include Directive
• Includes a static file in a JSP file, parsing the file's JSP elements.
– Syntax
<%@ include file="relativeURL" %>
The <%@ include %> directive inserts a file of text or code in a
JSP file at translation time, when the JSP file is compiled.
<%@ include %> process is static. A static include means that
the text of the included file is added to the JSP file.
The included file can be:
1. JSP file,
2. HTML file,
3. text file.
Taglib Directive
• Defines a tag library and prefix for the custom tags
used in the JSP page.
– Syntax
<%@ taglib uri="URIToTagLibrary"
prefix="tagPrefix" %>
<%@ taglib uri="http://thathost/tags"
prefix="public" %>
<public:loop>
</public:loop>
The <%@ taglib %> directive declares that the JSP
file uses custom tags, names the tag library that
defines them, and specifies their tag prefix.
<jsp:forward>
(Used in server redirection)
• Forwards a client request to an HTML file, JSP file, or
servlet for processing.
– Syntax
<jsp:forward page="{relativeURL | <%=
expression %>}" />
<jsp:forward page="{relativeURL | <%=
expression %>}" >
<jsp:param name="parameterName"
value="{parameterValue | <%=
expression %>}" />+
</jsp:forward>
<%@ page errorPage="error.jsp" %>
<%!
public double calculate(double amount, double
interest, int period) {
if(amount <= 0) {
throw new IllegalArgumentException("Amount
should be greater than 0: " + amount);
}
if(interest <= 0) {
throw new IllegalArgumentException("Interest
should be greater than 0: " + interest);
}
if(period <= 0) {
throw new IllegalArgumentException("Period should
be greater than 0: " + period);
}
return amount*Math.pow(1 + interest/100, period);
}
%>
Loan Calculator
compound.jsp <html>
<head>
<title>Compound</title>
</head>
<body style="font-family:verdana;font-size:10pt;">
<%@ include file="header.html" %>
<%
double amount =
Double.parseDouble(request.getParameter("amo
unt"));
double interest =
Double.parseDouble(request.getParameter("inte
rest"));
int period =
Integer.parseInt(request.getParameter("period"))
;
%>
<b>Pincipal using compound interest:</b>
<%= calculate(amount, interest, period) %>
<br/><br/>
<jsp:include page="footer.jsp"/>
</body>
</html>
Uses of JSP Constructs:
Using JavaBeans
• Scripting elements calling servlet
code directly
• Scripting elements calling servlet
code indirectly (by means of utility
classes)
• Beans
• Custom tags
• Servlet/JSP combo
(MVC architecture)
Simple
Application
Complex
Application
JavaBeans
• The other standard actions relate to
manipulation of JavaBeans within a JSP
page.
• JavaBeans is a component architecture.
• It dictates a set of rules that software
developers must follow to create reusable
components.
• A Bean is an instance of a class that was
coded following these rules.
• JSP interacts with Beans through tags
(naturally).
<jsp:useBean>
• Locates or instantiates a bean with a specific name and
scope.
<jsp:useBean
id="beanInstanceName"
scope="page|request|session|application"
{ class="package.class" |
type="package.class" |
class="package.class" type="package.class"
|
beanName="{package.class | <%= expression
%>}“
}
{ /> |
> other elements
</jsp:useBean>
}
Background: What Are Beans?
• Classes that follow certain conventions
– Must have a zero-argument (empty) constructor
– Should have no public instance variables (fields)
– Persistent values should be accessed through
methods called getXxx and setXxx
• If class has method getTitle that returns a String, class is
said to have a String property named title
• Boolean properties use isXxx instead of getXxx
• For more on beans, see
http://java.sun.com/beans/docs/
Basic Bean Use in JSP
• Format: <jsp:useBean id="name"
class="package.Class" />
• Purpose: Allow instantiation of classes without explicit Java
syntax
• Notes
– Simple interpretation: JSP action
<jsp:useBean id="book1" class="cwp.Book" />
can be thought of as equivalent to the scriptlet
<% cwp.Book book1 = new cwp.Book(); %>
– But useBean has two additional features
• Simplifies setting fields based on incoming request params
• Makes it easier to share beans
Attributes and Usage
• id="beanInstanceName"
A variable that identifies the bean in the scope you specify.
The name is case sensitive and must conform to the naming
conventions of the scripting language used in the JSP page
scope="page|request|session|application“
page One can use the bean within the JSP page with the
<jsp:useBean> element or any of the page's static include
files, until the page sends a response back to the client or
forwards a request to another resource
request One can use the bean from any JSP page processing
the same request, until a JSP page sends a response to the
client or forwards the request to another resource. One can
use the request object to access the bean, for example,
request.getAttribute(beanInstanceName).
Attributes and Usage ……
session One can use the bean from any JSP page
in the same session as the JSP page that created
the bean. The bean exists across the entire
session, and any page that participates in the
session can use it. The page in which you create
the bean must have a page directive with
session="true".
application One can use the bean from any JSP
page in the same application as the JSP page that
created the bean. The bean exists across an entire
JSP application, and any page in the application
can use the bean.
Different Scope
ApplicationApplication
SessionSession
RequestRequest
PagePage
Least visible
Most visible
Objects accessible only within pages
where they were created.
Objects accessible from pages
processing the request.
Objects accessible from pages
Belonging to the same session.
Objects accessible from pages
Belong to the same application.
<jsp:setProperty>• Sets a property value or values in a bean.
– Syntax
<jsp:setProperty name="beanInstanceName"
{ property="*" |
property="propertyName"
[ param="parameterName" ] |
property="propertyName" value="{string | <%=
expression %>}"
}
/>
Ex: <jsp:setProperty name="mybean" property="*"
/>
<jsp:setProperty name="mybean"
property="username" />
<jsp:setProperty name="mybean"
property="username" value="Steve" />
Setting Bean Properties:
Simple Example
• Format: <jsp: setProperty name="name"
property="property" value="value" />
• Purpose
– Allow setting of bean properties (i.e., calls to
setXxx) without explicit Java code
• Notes
– <jsp:setProperty name="book1"
property="title"
value="Core Servlets and JSP" />
is equivalent to the following scriptlet
<% book1.setTitle("Core Servlets and JSP"); %>
Jsp setproperty ….
The <jsp:setProperty> element sets the
value of one or more properties in a bean,
using the bean's setter methods. You must
declare the bean with<jsp:useBean>
before
you set a property value with
<jsp:setProperty>.
<jsp:getProperty>
• Gets the value of a bean property so that you can display it in a
result page.
– Syntax
<jsp:getProperty name="beanInstanceName“
property="propertyName" />
– Example:
<jsp:useBean id="calendar" scope="page"
class="employee.Calendar" />
<h2>
Calendar of <jsp:getProperty name="calendar"
property="username" />
</h2>
The <jsp:getProperty> element gets a bean property value using the
property's getter methods and displays the property value in a JSP
page. You must create or locate a bean with <jsp:useBean> before
you use <jsp:getProperty>.
Jsp with Beans
public class MessageBean {
private String message = "No Message";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JavaBeans with JSP Page
<jsp:useBean id="firstBean" scope="session"
class="packBeans.MessageBean"/>
<jsp:setProperty name="firstBean"
property="message"
value="This is a message from a
bean" />
<H1>Message:
<I><font color="#0000FF" size=+3>
<jsp:getProperty name="firstBean"
property="message" />
</I></font>
</H1>
Handling Forms with JSP
package packBeans;
public class NameBean {
private String name;
public NameBean() {
name = null;
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
}
JSP Form
<jsp:useBean id='nb' scope='session'
class=‘packBeans.NameBean'/>
<jsp:setProperty name='nb' property="*"/>
<HTML>
<BODY>
<H1>Please enter your name to be registered to JSP Course?
</H1>
<FORM method="get">
<INPUT type="text" name="name" size="25">
<INPUT type="submit" value="Submit">
</FORM>
<% if ( request.getParameter("name") != null ) } %>
<%=
"Click<a href=GetName.jsp> here</a> to confirm your
registration"
%>
<% } %>
</BODY>
</HTML>
JSP Results
<jsp:useBean id='nb'
scope="session“class=“packBeans.NameBean"/>
<HTML>
<HEAD>
<TITLE>Registered Name</TITLE>
</HEAD>
<BODY>
<jsp:getProperty name="nb" property="name"/>
</BODY>
</HTML>
Work with the Buffer
• When the page is being processed, the data is
stored in the buffer instead of being directly sent
to the client browser.
<<htmlhtml>>
This is a test of the bufferThis is a test of the buffer<<brbr/>/>
<%<%
out.flush();out.flush();
for (int x=0; x < 100000000; x++);for (int x=0; x < 100000000; x++);
out.print("This test is generated about 5 secondsout.print("This test is generated about 5 seconds
later.");later.");
out.flush();out.flush();
%>%>
</</htmlhtml>>
Working with Session object
• The session object has many useful methods
that can alter or obtain information about the
current session.
– setMaxInactiveInterval(second)
<<htmlhtml><><headhead>>
<<titletitle>>Session ValuesSession Values</</titletitle>>
</</headhead><><bodybody>>
<%<%
session.setMaxInactiveInterval(10);session.setMaxInactiveInterval(10);
String name = (String)String name = (String)
session.getAttribute("username");session.getAttribute("username");
out.print("Welcome to my site " + name + "<br>");out.print("Welcome to my site " + name + "<br>");
%>%>
</</bodybody></></htmlhtml>>
Model View Controller
1. Model: This is business logic of applications,
responsible for performing the actual work conducted
by the application. This unit deals with the modeling of
real-world problem and doesn’t have any idea about
how it is being displayed to the user.
2. View: This is presentation logic of the application
responsible for rendering the information or data of the
application. It may have little or no programming logic
at all.
MVC
3.Controller: This is the request processing logic of the
application,& mainly responsible for coupling between both
the model and view together, so as to perform the operations.
• It is like a traffic controller directing request to the
corresponding resources and forwarding appropriate
response to the user.
• Finally the goal of MVC is the separation of content
presentation (view), and content generation (Model) there by
developing maintainable, flexible and extensible application.
• Java Programmers can concentrate on writing java code
(model and controller) and web designers could concentrate
on using dream weaver, Photoshop to build fabulous-looking
web pages (for view)
MVC
Controller
Model
View
Data Base5:forwardtoview
2: Invoke
3: retrieve/store
data4: Get result
1: request
6:response
User
Java Server Pages
• Model 2 Architecture to serve dynamic content
– Model: Enterprise Beans with data in the DBMS
• JavaBean: a class that encapsulates objects and can be displayed
graphically
– Controller: Servlets create beans, decide which JSP to
return, do the bulk of the processing
– View: The JSPs generated in the presentation layer (the
browser)
53
MVC Benefits
• Clarity of design
– easier to implement and maintain
• Modularity
– changes to one don't affect the others
– can develop in parallel once you have the
interfaces
• Multiple views
– games, spreadsheets, powerpoint, Eclipse,
UML reverse engineering, ….
54
MVC
Design Pattern
Architecture

More Related Content

PPTX
Spring boot
PPTX
Proxy Design Pattern
ODP
Testing RESTful Webservices using the REST-assured framework
PPT
Test Automation Framework Designs
PPT
Protege tutorial
PPTX
Self-learned Relevancy with Apache Solr
PPTX
C#-LINQ-and-Lambda-Expression
PDF
Web Development with Python and Django
Spring boot
Proxy Design Pattern
Testing RESTful Webservices using the REST-assured framework
Test Automation Framework Designs
Protege tutorial
Self-learned Relevancy with Apache Solr
C#-LINQ-and-Lambda-Expression
Web Development with Python and Django

What's hot (20)

PDF
Single Page Applications
PDF
ORM: Object-relational mapping
PPTX
Introduction to Node.js
PDF
Page Object Model and Implementation in Selenium
PPT
Flyweight pattern
PDF
Seoul (Commercial Real-Estate) Market Analysis Pipeline
PDF
REST APIs with Spring
PPTX
Introduction to Spring Boot
PPTX
Server side programming
PPTX
Spring boot Introduction
PPTX
J2ee seminar
PPT
Java beans
PDF
現状分析→価値開発→仕様化 To be
PDF
Nodejs presentation
PDF
Spring Framework - MVC
PPTX
XSLT presentation
PPTX
Microservice vs. Monolithic Architecture
PPTX
Data driven Automation Framework with Selenium
PDF
AngularJS 101 - Everything you need to know to get started
Single Page Applications
ORM: Object-relational mapping
Introduction to Node.js
Page Object Model and Implementation in Selenium
Flyweight pattern
Seoul (Commercial Real-Estate) Market Analysis Pipeline
REST APIs with Spring
Introduction to Spring Boot
Server side programming
Spring boot Introduction
J2ee seminar
Java beans
現状分析→価値開発→仕様化 To be
Nodejs presentation
Spring Framework - MVC
XSLT presentation
Microservice vs. Monolithic Architecture
Data driven Automation Framework with Selenium
AngularJS 101 - Everything you need to know to get started
Ad

Viewers also liked (9)

PPT
HTML By K.Sasidhar
PPT
Jsp Presentation +Mufix "3"
PPS
Jsp element
PPTX
Jsp Introduction Tutorial
PPTX
Java/Servlet/JSP/JDBC
PPTX
Jsp presentation
PPT
Jsp ppt
PPT
Java Servlets
HTML By K.Sasidhar
Jsp Presentation +Mufix "3"
Jsp element
Jsp Introduction Tutorial
Java/Servlet/JSP/JDBC
Jsp presentation
Jsp ppt
Java Servlets
Ad

Similar to Jsp sasidhar (20)

PPTX
JSP - Java Server Page
PPT
Java serverpages
PPTX
PPTX
21CS642 Module 4_2 JSP PPT.pptx VI SEM CSE
PPTX
JSP.pptx
PPTX
Advance java session 10
PPTX
JSP- JAVA SERVER PAGES
PPTX
WT Unit-Vuufvmjn dissimilating Dunkirk k
PPTX
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
PPTX
Java Server Pages
PPSX
JSP - Part 2 (Final)
PPSX
JSP - Part 1
PPTX
Session 37 - JSP - Part 2 (final)
PPTX
JSP AND XML USING JAVA WITH GET AND POST METHODS
PPT
Java Server Pages
PPTX
Session 36 - JSP - Part 1
PPTX
18CSC311J Web Design and Development UNIT-3
JSP - Java Server Page
Java serverpages
21CS642 Module 4_2 JSP PPT.pptx VI SEM CSE
JSP.pptx
Advance java session 10
JSP- JAVA SERVER PAGES
WT Unit-Vuufvmjn dissimilating Dunkirk k
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Java Server Pages
JSP - Part 2 (Final)
JSP - Part 1
Session 37 - JSP - Part 2 (final)
JSP AND XML USING JAVA WITH GET AND POST METHODS
Java Server Pages
Session 36 - JSP - Part 1
18CSC311J Web Design and Development UNIT-3

More from Sasidhar Kothuru (20)

PPT
Spsl vi unit final
PPT
Spsl iv unit final
PPT
Spsl v unit - final
PPT
Spsl iv unit final
PPT
Spsl v unit - final
PPT
Spsl by sasidhar 3 unit
PPT
Spsl unit1
PPT
Spsl II unit
PPT
Jdbc sasidhar
PPT
PPT
Servers names
PPT
Servers names
PPT
Web Technologies -- Servlets 4 unit slides
DOC
Xml quiz 3 unit
DOC
Web technologies quiz questions - unit1,2
DOC
Web technologies 4th unit quiz
DOC
Xml quiz 3 unit
DOC
Web technologies quiz questions - unit1,2
PPT
Xml sasidhar
PPT
Java script -23jan2015
Spsl vi unit final
Spsl iv unit final
Spsl v unit - final
Spsl iv unit final
Spsl v unit - final
Spsl by sasidhar 3 unit
Spsl unit1
Spsl II unit
Jdbc sasidhar
Servers names
Servers names
Web Technologies -- Servlets 4 unit slides
Xml quiz 3 unit
Web technologies quiz questions - unit1,2
Web technologies 4th unit quiz
Xml quiz 3 unit
Web technologies quiz questions - unit1,2
Xml sasidhar
Java script -23jan2015

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
A Presentation on Artificial Intelligence
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Encapsulation theory and applications.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPT
Teaching material agriculture food technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Cloud computing and distributed systems.
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Modernizing your data center with Dell and AMD
Understanding_Digital_Forensics_Presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
cuic standard and advanced reporting.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Diabetes mellitus diagnosis method based random forest with bat algorithm
A Presentation on Artificial Intelligence
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
NewMind AI Weekly Chronicles - August'25 Week I
Per capita expenditure prediction using model stacking based on satellite ima...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Encapsulation theory and applications.pdf
NewMind AI Monthly Chronicles - July 2025
Teaching material agriculture food technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
Cloud computing and distributed systems.
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Modernizing your data center with Dell and AMD

Jsp sasidhar

  • 2. servlets • Server side Java programs • Solve scalability issue • serlvets are run on threads of execution not separate processes • Solve portability issue • runs on every platform that supports Java • supported by all most popular web servers • Issues: • html tags are embedded in java programs within out.print() statements
  • 3. JSP -- Introduction • server-side technology • separates dynamic content from static content of a page – Java scriptlets embedded into html-like page • Separates the work of – java programmers – page authors
  • 4. Introduction • Java Server Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically- generated content • Developed by Sun Micro Systems in 1999. • Defines interaction between the server and JSP and describes the format and syntax of the page.
  • 5. JSP page • A page created by the web developer that includes JSP technology-specific and custom tags, in combination with other static (HTML or XML) tags. • A JSP page has the extension .jsp or .jspx; • This signals to the web server that the JSP engine will process elements on this page. • Using the .xml deployment descriptor, additional extensions can be associated with the JSP engine.
  • 6. Advantages of JSP • Provides a powerful and flexible mechanism to produce dynamic web pages. • It allows the creation of custom tag libraries to meet the specific needs of the project. • It provides built-in support of HTTP session management. • Can be integrated with : JDBC API, Thread API, EJB API etc..
  • 7. JSP notations • <% … %> jsp scriplet  a fragment of code that run when the user request the webpage. • < %= > delimeter used for expressions • <%@ > jsp directives
  • 8. Anatomy of a jsp page <%@page contenttype = “text/html” language = “java%”> <%@page import = “java.util.Date” session = “false”%> Jsp elements <html> <head> <title> simple jsp page demo</title> </head> <body> <h3> current time is : </h3> Template data <%= new Date()%> -- > jsp elements </body> </html> Template data %@ is jsp directive %= is jsp element
  • 9. In a simple way <HTML> <BODY> Hello! The time is now <%= new java.util.Date() %> </BODY> </HTML>
  • 10. Client and Server with JSP
  • 11. Java Server Pages (JSP) in detail Client’s Computer Server 1.Browser requests HTML 7. Server sends HTML back to browser servlet servlet class 5.The servlet runs and generates HTML Java Engine 6. Java Engine sends HTML to server 2. Server sends requests to Java Engine 3. If needed, the Java Engine reads the .jsp file 4. The JSP is turned into a servlet, compiled, and loaded Bean
  • 13. Translation Time • A JSP application is usually a collection of JSP files, HTML files, graphics and other resources. • A JSP page is compiled when your user loads it into a Web browser 1. When the user loads the page for the first time, the files that make up the application are all translated together, without any dynamic data, into one Java source file (a .java file) 2. The .java file is compiled to a .class file. In most implementations, the .java file is a Java servlet that complies with the Java Servlet API.
  • 14. JSP Elements • Declarations <%! code %> <jsp:declaration> </jsp:declaration > • Expressions <%= expression %> <jsp:expression> </jsp:expression> • Scriplets <% code %> <jsp:scriplet> </jsp:scriplet >
  • 15. Declaration • Declares a variable or method valid in the scripting language used in the JSP page. – Syntax <%! declaration; [ declaration; ]+ ... %> – Examples <%! String destin; %> <%! Public String getDestination() {return destin;}%> <%! Circle a = new Circle(2.0); %> – You can declare any number of variables or methods within one declaration element, as long as you end each declaration with a semicolon. – The declaration must be valid in the Java programming language.
  • 16. Declaration Example <HTML> <HEAD><TITLE>JSP Declarations</TITLE></HEAD> <BODY><H1>JSP Declarations</H1> <%! private int keepCount = 0; %> <H2> Page accessed: <%= ++keepCount %> times </H2> </BODY> </HTML>
  • 17. Predefined Variable – Implicit Objects • request – Object of HttpServletRequest (request parameters, HTTP headers, cookies • response – Object of HttpServletResponse • out - Object of PrintWriter buffered version JspWriter • session - Object of HttpSession associated with the request • application - Object of ServletContext shared by all servlets in the engine • config - Object of ServletConfig • pageContext - Object of PageContext in JSP for a single point of access page – variable synonym for this object
  • 18. Expression • Contains an expression valid in the scripting language used in the JSP page. – Syntax <%= expression %> <%! String name = new String(“JSP World”); %> <%! public String getName() { return name; } %> <B><%= getName() %></B> Description: An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. – Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSPfile. Expressions are evaluated from left to right.
  • 19. Expression Example <HTML> <HEAD> <TITLE>JSP Expressions</TITLE> </HEAD> <BODY> <H2>JSP Expressions</H2> <UL> <LI>Current time: <%= new java.util.Date() %> <LI>Your hostname: <%= request.getRemoteHost() %> <LI>Your session ID: <%= session.getId() %> </UL> </BODY> </HTML>
  • 20. Scriptlet • Contains a code fragment valid in the page scripting language. – Syntax <% code fragment %> <% String var1 = request.getParameter("name"); out.println(var1); %> This code will be placed in the generated servlet method: _jspService()
  • 21. Scriplet Example <HTML> <HEAD><TITLE>Weather</TITLE></HEAD> <BODY> <H2>Today's weather</H2> <% if (Math.random() < 0.5) { %> Today will be a <B>suny</B> day! <% } else { %> Today will be a <B>windy</B> day! <% } %> </BODY> </HTML>
  • 22. JSP Scriptlets Example <% for (int i=100; i>=0; i--) { %> <%= i %> The numbers in decending order are: <br> <% } %>
  • 23. Another example: JSP Tags + HTML Tags <h2>Table of Square Roots</h2> <table border=2> <tr> <td><b>Number</b></td> <td><b>Square Root</b></td> </tr> <% for (int n=0; n<=100; n++) { %> <tr> <td><%=n%></td> <td><%=Math.sqrt(n)%></td> </tr> <% } %> </table>
  • 24. JSP Page Directive • Directives are messages to the JSP container and do not produce output into the current output stream – Syntax: <%@ directive attribute=“value” %> <%@ directive attribute1=“value1” attribute1 =“value2” … %> There are three types of directives: 1. page 2. include 3. Taglib XML form: <jsp:directive.directiveType attribute=“value” />
  • 25. Purpose of the page Directive • Give high-level information about the servlet that will result from the JSP page • Can control – Which classes are imported – What class the servlet extends – What MIME type is generated ( Multipurpose Internet Mail extensions ) – How multithreading is handled – If the servlet participates in sessions – The size and behavior of the output buffer – What page handles unexpected errors
  • 26. Page Directive • Defines attributes that apply to an entire JSP page. <%@ page [ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*}, ..." ] [ session="true|false" ] [ buffer="none|8kb|sizekb" ] [ autoFlush="true|false" ] [ isThreadSafe="true|false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType="mimeType [ ;charset=characterSet ]" [ isErrorPage="true|false" ] %>
  • 27. Include Directive • Includes a static file in a JSP file, parsing the file's JSP elements. – Syntax <%@ include file="relativeURL" %> The <%@ include %> directive inserts a file of text or code in a JSP file at translation time, when the JSP file is compiled. <%@ include %> process is static. A static include means that the text of the included file is added to the JSP file. The included file can be: 1. JSP file, 2. HTML file, 3. text file.
  • 28. Taglib Directive • Defines a tag library and prefix for the custom tags used in the JSP page. – Syntax <%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %> <%@ taglib uri="http://thathost/tags" prefix="public" %> <public:loop> </public:loop> The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix.
  • 29. <jsp:forward> (Used in server redirection) • Forwards a client request to an HTML file, JSP file, or servlet for processing. – Syntax <jsp:forward page="{relativeURL | <%= expression %>}" /> <jsp:forward page="{relativeURL | <%= expression %>}" > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ </jsp:forward>
  • 30. <%@ page errorPage="error.jsp" %> <%! public double calculate(double amount, double interest, int period) { if(amount <= 0) { throw new IllegalArgumentException("Amount should be greater than 0: " + amount); } if(interest <= 0) { throw new IllegalArgumentException("Interest should be greater than 0: " + interest); } if(period <= 0) { throw new IllegalArgumentException("Period should be greater than 0: " + period); } return amount*Math.pow(1 + interest/100, period); } %> Loan Calculator compound.jsp <html> <head> <title>Compound</title> </head> <body style="font-family:verdana;font-size:10pt;"> <%@ include file="header.html" %> <% double amount = Double.parseDouble(request.getParameter("amo unt")); double interest = Double.parseDouble(request.getParameter("inte rest")); int period = Integer.parseInt(request.getParameter("period")) ; %> <b>Pincipal using compound interest:</b> <%= calculate(amount, interest, period) %> <br/><br/> <jsp:include page="footer.jsp"/> </body> </html>
  • 31. Uses of JSP Constructs: Using JavaBeans • Scripting elements calling servlet code directly • Scripting elements calling servlet code indirectly (by means of utility classes) • Beans • Custom tags • Servlet/JSP combo (MVC architecture) Simple Application Complex Application
  • 32. JavaBeans • The other standard actions relate to manipulation of JavaBeans within a JSP page. • JavaBeans is a component architecture. • It dictates a set of rules that software developers must follow to create reusable components. • A Bean is an instance of a class that was coded following these rules. • JSP interacts with Beans through tags (naturally).
  • 33. <jsp:useBean> • Locates or instantiates a bean with a specific name and scope. <jsp:useBean id="beanInstanceName" scope="page|request|session|application" { class="package.class" | type="package.class" | class="package.class" type="package.class" | beanName="{package.class | <%= expression %>}“ } { /> | > other elements </jsp:useBean> }
  • 34. Background: What Are Beans? • Classes that follow certain conventions – Must have a zero-argument (empty) constructor – Should have no public instance variables (fields) – Persistent values should be accessed through methods called getXxx and setXxx • If class has method getTitle that returns a String, class is said to have a String property named title • Boolean properties use isXxx instead of getXxx • For more on beans, see http://java.sun.com/beans/docs/
  • 35. Basic Bean Use in JSP • Format: <jsp:useBean id="name" class="package.Class" /> • Purpose: Allow instantiation of classes without explicit Java syntax • Notes – Simple interpretation: JSP action <jsp:useBean id="book1" class="cwp.Book" /> can be thought of as equivalent to the scriptlet <% cwp.Book book1 = new cwp.Book(); %> – But useBean has two additional features • Simplifies setting fields based on incoming request params • Makes it easier to share beans
  • 36. Attributes and Usage • id="beanInstanceName" A variable that identifies the bean in the scope you specify. The name is case sensitive and must conform to the naming conventions of the scripting language used in the JSP page scope="page|request|session|application“ page One can use the bean within the JSP page with the <jsp:useBean> element or any of the page's static include files, until the page sends a response back to the client or forwards a request to another resource request One can use the bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another resource. One can use the request object to access the bean, for example, request.getAttribute(beanInstanceName).
  • 37. Attributes and Usage …… session One can use the bean from any JSP page in the same session as the JSP page that created the bean. The bean exists across the entire session, and any page that participates in the session can use it. The page in which you create the bean must have a page directive with session="true". application One can use the bean from any JSP page in the same application as the JSP page that created the bean. The bean exists across an entire JSP application, and any page in the application can use the bean.
  • 38. Different Scope ApplicationApplication SessionSession RequestRequest PagePage Least visible Most visible Objects accessible only within pages where they were created. Objects accessible from pages processing the request. Objects accessible from pages Belonging to the same session. Objects accessible from pages Belong to the same application.
  • 39. <jsp:setProperty>• Sets a property value or values in a bean. – Syntax <jsp:setProperty name="beanInstanceName" { property="*" | property="propertyName" [ param="parameterName" ] | property="propertyName" value="{string | <%= expression %>}" } /> Ex: <jsp:setProperty name="mybean" property="*" /> <jsp:setProperty name="mybean" property="username" /> <jsp:setProperty name="mybean" property="username" value="Steve" />
  • 40. Setting Bean Properties: Simple Example • Format: <jsp: setProperty name="name" property="property" value="value" /> • Purpose – Allow setting of bean properties (i.e., calls to setXxx) without explicit Java code • Notes – <jsp:setProperty name="book1" property="title" value="Core Servlets and JSP" /> is equivalent to the following scriptlet <% book1.setTitle("Core Servlets and JSP"); %>
  • 41. Jsp setproperty …. The <jsp:setProperty> element sets the value of one or more properties in a bean, using the bean's setter methods. You must declare the bean with<jsp:useBean> before you set a property value with <jsp:setProperty>.
  • 42. <jsp:getProperty> • Gets the value of a bean property so that you can display it in a result page. – Syntax <jsp:getProperty name="beanInstanceName“ property="propertyName" /> – Example: <jsp:useBean id="calendar" scope="page" class="employee.Calendar" /> <h2> Calendar of <jsp:getProperty name="calendar" property="username" /> </h2> The <jsp:getProperty> element gets a bean property value using the property's getter methods and displays the property value in a JSP page. You must create or locate a bean with <jsp:useBean> before you use <jsp:getProperty>.
  • 43. Jsp with Beans public class MessageBean { private String message = "No Message"; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
  • 44. JavaBeans with JSP Page <jsp:useBean id="firstBean" scope="session" class="packBeans.MessageBean"/> <jsp:setProperty name="firstBean" property="message" value="This is a message from a bean" /> <H1>Message: <I><font color="#0000FF" size=+3> <jsp:getProperty name="firstBean" property="message" /> </I></font> </H1>
  • 45. Handling Forms with JSP package packBeans; public class NameBean { private String name; public NameBean() { name = null; } public String getName() { return name; } public void setName(String aName) { name = aName; } }
  • 46. JSP Form <jsp:useBean id='nb' scope='session' class=‘packBeans.NameBean'/> <jsp:setProperty name='nb' property="*"/> <HTML> <BODY> <H1>Please enter your name to be registered to JSP Course? </H1> <FORM method="get"> <INPUT type="text" name="name" size="25"> <INPUT type="submit" value="Submit"> </FORM> <% if ( request.getParameter("name") != null ) } %> <%= "Click<a href=GetName.jsp> here</a> to confirm your registration" %> <% } %> </BODY> </HTML>
  • 47. JSP Results <jsp:useBean id='nb' scope="session“class=“packBeans.NameBean"/> <HTML> <HEAD> <TITLE>Registered Name</TITLE> </HEAD> <BODY> <jsp:getProperty name="nb" property="name"/> </BODY> </HTML>
  • 48. Work with the Buffer • When the page is being processed, the data is stored in the buffer instead of being directly sent to the client browser. <<htmlhtml>> This is a test of the bufferThis is a test of the buffer<<brbr/>/> <%<% out.flush();out.flush(); for (int x=0; x < 100000000; x++);for (int x=0; x < 100000000; x++); out.print("This test is generated about 5 secondsout.print("This test is generated about 5 seconds later.");later."); out.flush();out.flush(); %>%> </</htmlhtml>>
  • 49. Working with Session object • The session object has many useful methods that can alter or obtain information about the current session. – setMaxInactiveInterval(second) <<htmlhtml><><headhead>> <<titletitle>>Session ValuesSession Values</</titletitle>> </</headhead><><bodybody>> <%<% session.setMaxInactiveInterval(10);session.setMaxInactiveInterval(10); String name = (String)String name = (String) session.getAttribute("username");session.getAttribute("username"); out.print("Welcome to my site " + name + "<br>");out.print("Welcome to my site " + name + "<br>"); %>%> </</bodybody></></htmlhtml>>
  • 50. Model View Controller 1. Model: This is business logic of applications, responsible for performing the actual work conducted by the application. This unit deals with the modeling of real-world problem and doesn’t have any idea about how it is being displayed to the user. 2. View: This is presentation logic of the application responsible for rendering the information or data of the application. It may have little or no programming logic at all.
  • 51. MVC 3.Controller: This is the request processing logic of the application,& mainly responsible for coupling between both the model and view together, so as to perform the operations. • It is like a traffic controller directing request to the corresponding resources and forwarding appropriate response to the user. • Finally the goal of MVC is the separation of content presentation (view), and content generation (Model) there by developing maintainable, flexible and extensible application. • Java Programmers can concentrate on writing java code (model and controller) and web designers could concentrate on using dream weaver, Photoshop to build fabulous-looking web pages (for view)
  • 52. MVC Controller Model View Data Base5:forwardtoview 2: Invoke 3: retrieve/store data4: Get result 1: request 6:response User
  • 53. Java Server Pages • Model 2 Architecture to serve dynamic content – Model: Enterprise Beans with data in the DBMS • JavaBean: a class that encapsulates objects and can be displayed graphically – Controller: Servlets create beans, decide which JSP to return, do the bulk of the processing – View: The JSPs generated in the presentation layer (the browser) 53
  • 54. MVC Benefits • Clarity of design – easier to implement and maintain • Modularity – changes to one don't affect the others – can develop in parallel once you have the interfaces • Multiple views – games, spreadsheets, powerpoint, Eclipse, UML reverse engineering, …. 54

Editor's Notes

  • #31: Potential Damages: 1. Change orders placed by the client (Instead of 500 widgets he can make the order 50,000 widgets) 2. Change meeting venues to send people on wild goose chases
  • #35: You can satisfy the requirement of the zero-arg constructor either by explicitly defining such a constructor or by omitting all constructors. Beans created by servlets can have arbitrary constructors I hope you already follow the practice of using accessor methods instead of allowing direct access to fields.