SlideShare une entreprise Scribd logo
1  sur  56
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

Contenu connexe

Tendances

Tendances (20)

Advanced Cascading Style Sheets
Advanced Cascading Style SheetsAdvanced Cascading Style Sheets
Advanced Cascading Style Sheets
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).ppt
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
What is Ajax technology?
What is Ajax technology?What is Ajax technology?
What is Ajax technology?
 
HTML and CSS crash course!
HTML and CSS crash course!HTML and CSS crash course!
HTML and CSS crash course!
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
jQuery
jQueryjQuery
jQuery
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Express JS
Express JSExpress JS
Express JS
 
web development
web developmentweb development
web development
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 

En vedette (9)

HTML By K.Sasidhar
HTML By K.SasidharHTML By K.Sasidhar
HTML By K.Sasidhar
 
Jsp Presentation +Mufix "3"
Jsp Presentation +Mufix "3"Jsp Presentation +Mufix "3"
Jsp Presentation +Mufix "3"
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jdbc
JdbcJdbc
Jdbc
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

Similaire à JSP - Java Server Pages Overview

JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server PageVipin Yadav
 
Java serverpages
Java serverpagesJava serverpages
Java serverpagesAmit Kumar
 
Advance java session 10
Advance java session 10Advance java session 10
Advance java session 10Smita B Kumar
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESYoga Raja
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Ayes Chinmay
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final) Hitesh-Java
 
Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)PawanMM
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSJSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSbharathiv53
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1PawanMM
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentationLakshmi R
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdfArumugam90
 

Similaire à JSP - Java Server Pages Overview (20)

JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Java serverpages
Java serverpagesJava serverpages
Java serverpages
 
Jsp
JspJsp
Jsp
 
Jsp1
Jsp1Jsp1
Jsp1
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
Advance java session 10
Advance java session 10Advance java session 10
Advance java session 10
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
Jsp
JspJsp
Jsp
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)Session 37 - JSP - Part 2 (final)
Session 37 - JSP - Part 2 (final)
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODSJSP AND XML USING JAVA WITH GET AND POST METHODS
JSP AND XML USING JAVA WITH GET AND POST METHODS
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
 

Plus de Sasidhar Kothuru (20)

Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Spsl by sasidhar 3 unit
Spsl by sasidhar  3 unitSpsl by sasidhar  3 unit
Spsl by sasidhar 3 unit
 
Spsl unit1
Spsl   unit1Spsl   unit1
Spsl unit1
 
Spsl II unit
Spsl   II unitSpsl   II unit
Spsl II unit
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Servlets
ServletsServlets
Servlets
 
Servers names
Servers namesServers names
Servers names
 
Servers names
Servers namesServers names
Servers names
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
 
Xml quiz 3 unit
Xml quiz   3 unitXml quiz   3 unit
Xml quiz 3 unit
 
Web technologies quiz questions - unit1,2
Web technologies quiz questions  - unit1,2Web technologies quiz questions  - unit1,2
Web technologies quiz questions - unit1,2
 
Web technologies 4th unit quiz
Web technologies 4th unit quizWeb technologies 4th unit quiz
Web technologies 4th unit quiz
 
Xml quiz 3 unit
Xml quiz   3 unitXml quiz   3 unit
Xml quiz 3 unit
 
Web technologies quiz questions - unit1,2
Web technologies quiz questions  - unit1,2Web technologies quiz questions  - unit1,2
Web technologies quiz questions - unit1,2
 
Xml sasidhar
Xml  sasidharXml  sasidhar
Xml sasidhar
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 

Dernier

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Dernier (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

JSP - Java Server Pages Overview

  • 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

Notes de l'éditeur

  1. 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
  2. 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.