Professional Documents
Culture Documents
the View:
Servlets and JSP™
1
Agenda
2
The History of Dynamic Content
Creation on the Internet.
Lets turn to the real world to understand the business need for JSP.
HTTP – a request response protocol, stateless.
The internet initially provided static content.
Programmers needed a hook into the web server to dynamically modify requests.
Common Gateway Interface:
- access resources (file system and database)
- not good for a distributed environment.
- a separate process is needed for every request – does not scale well.
Servlets:
- Platform and web server dependant.
- Can use Java APIs to access enterprise resources.
- Build on existing skills.
- Servlets can be loaded into memory and reused.
- Requests use only one light weight thread.
- Servlet context allows pooling of enterprise resources.
- Session API used to overcome the limitations of the stateless HTTP protocol.
3
What Are Servlets?
Servlets are Java’s answer to CGI/Perl...
§ Server side Java™ program that extends the
functionality of a HTTP Web Server,
…respond to web server requests
§ Used to generate dynamic HTML Browser
Applications
§ Alternative for CGI, NSAPI, ISAPI, etc.
§ Available and running on all major web servers
§ Platform and Web Server Independent
§ Simple architecture
§ Managed by container
§ Very rich platform facilities available
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
Although http is a standard protocol, each browser has it’s own oddities. It’s a webmaster’s
nightmare to deal with this. Typically, instead of a static set of html pages, pages are generated
on the fly for browser specific customization.
Also, in several situations it may be necessary to serve a page which is based on a template
and some entries filled in dynamically.
Different alternatives exist. You may use webserver extensions like NSAPI,
ISAPI, Apache modules, etc. However, these work only with that respective webserver and
will be difficult to migrate to a different webserver in the future. CGI is a cross platform and
cross server way of solving the problem but CGI has many performance issues.
Servlets and JSP™ is a superior alternative. They are available on almost all webservers and
they open up the “Java world” to the webservers.
4
Why Servlets?
5
Servlets and JSP™s Run in Web Container
J2SE
RMI/IIOP
RMI/IIOP
JDBC
JDBC
JavaMail JavaMail
JNDI
JMS
JNDI
JTA
JMS
JTA
App Client
Container JAF JAF
App HTTP/
Client HTTPS
J2SE
RMI
RMI/IIOP
JDBC
JNDI
JMS
J2SE J2SE
Database
6
Servlets vs. CGI
Request CGI1
Child for CGI1
Request CGI2
CGI
Based Child for CGI2
Webserver
Request CGI1
Child for CGI1
Request Servlet1
Servlet Based Webserver
Notice in the illustration that although the same page was referenced again, a
new process was created to handle the request since that’s the inherent way it’s
done using CGI. Process creation as we all understand is very expensive. In
the servlet model a new thread is created , which is lightweight.
With CGI you make a connection/disconnection for every request. Every
connection is handled by a newly created process.
With Servlets the connections persist and there is no overhead of starting a
new process.
7
Servlet Basics
• Well-defined lifecycle
• Managed by container
• Loaded on demand
• Unloaded by container at any time
• Multi-threaded
Servlets are often referred to as faceless applets i.e. they do not have a GUI,
but have a well defined lifecycle just like an applet.
8
Servlet Classes
HttpServlet
extends
9
Illustration of client Request
Server
Session
Request
init()
service()
destroy()
Response
10
The Servlet Lifecycle
The destroy() method may be called on the servlet prior to server shutdown. It
should not be assumed that the servlet is destroyed only on server shutdown
although that’s typically what happens.
11
Request, Response Objects
Server
Request
Servlet
Response
Request Object:
Encapsulates all information from the client
Provides access to
request headers
InputStream or Reader containing data from the client
CGI Like information
form data and query parameters
server specific parameters such as SSL information
Response Object:
Encapsulates all communication back to the client
Provides access to
response headers
OutputStream to write data to the client
setting cookies
Convenience method for sending redirects, error pages, etc.
12
Request and Response Parameters
•Request
•HTTP request headers
•InputStream or reader
•Response
•HTTP response headers
•OutputStream or writer
13
Anatomy of a Request
14
Code for a Simple Servlet
15
What is JSP?
The problem with servlets is that too much of HTML code is embedded in a
Java program violating the cardinal rule of keeping program logic and
presentation separate.
What JSPs do is overcome this problem. The JSP™ contains all the
presentation and only some logic. Most of the program logic is tucked away in
the programs which are invoked by it.
Whereas Servlets have HTML code in Java, JSP™ has Java code in HTML.
16
How do JSP™s Work?
17
HTML to Java Bean Mapping
Java Bean
HTTP
Requests
JSP™ Page Java Bean
HTTP
Response
Java Bean
JSP™ (Developer
View)
Check if page needs
to be recompiled.
JSP™ Page
HTTP
Requests Web Server
Compile page
into servlet Java Bean
HTTP
Response
JAVA Java Bean
Load if needed
Servlet
And run servlet
Java Bean
JSP™ (Physical View)
The JSP™ page contains Fixed template Data to Java Bean Mapping.
18
JSP™ vs Servlet
• JSP
– Presentation centric
– HTML or XML with embedded Java
• Servlet
– Processing centric
– Java with HTML statements
19
Example Servlet
20
Example JSP
<html>
Hello World!<br>
<jsp:useBean id="clock"
class=“calendar.JspCalendar” />
Today is
<ul>
<li>Day of month:
<%= clock.getDayOfMonth() %>
</ul>
</html>
21
Java Server Pages
Fundamentals
– Model 2:
22
What facilities does JSP™ give page
designer to build pages and access
Java beans ?
• The JavaServer Pages specification
includes:
– Standard directives.
– Standard JSP™ Tags.
– Scripting elements.
– Implicit Objects.
– A portable tag extension mechanism.
23
Directives
24
JSP™ Standard Tags
UseBean locates or create a bean of the specified class and gives it the
appropriate scope.
Object lifetime.
-page : PageContext : – page Scope
-request : HttpServletResponse – request Scope
-session : HttpSession – session scope.
-Application: ServletContext – application scope.
GetProperty and SetProperty – talk about param, or value
Jsp:include or jsp:forward – must not write to output buffer.
25
JSP™ Scripting Elements
• Declarations
<%! QuoteBean q; %>
• Scriptlets
<% q = new QuoteBean(); %>
• Expressions
<%= q.getQuote(“SUNW”); %>
Scriptlets and expressions look similar. You can assume that expressions are
returning a value. So they can be used in other statements, assignments,
expressions, etc.
26
Implicit Objects
27
JSP™ Sample
Action <html>
<br>
<h3> The event name is: <jsp:getProperty name="event" property="name" /></h3>
<h3> The event description is: <%= event.getDescription() %></h3>
Expression <br>
<br>
<% if (event.getName().equalsIgnoreCase("appointment")) {
event.processAppointment(request.getParameter(“name”); %>
<jsp:include page="appointment.html" />
Scriptlet
<% }
else { %>
<jsp:include page="regular.html" /> Implicit
<% } %>
Object
</html>
28
Portable Tag Extension Mechanism
29
Example using Tag Library
<html>
<%@ taglib uri=http://acme.com/taglibs/simpleDB.tld” prefix=“x” %>
<x:queryBlock connData=“conData1”>
<x:queryStatement>
SELECT ACCOUNT, BALANCE, FROM …
</x:queryStatement>
The top 10 accounts and balances are:
<table>
<tr><th>ACCOUNT</th><th>BALANCE</th></tr>
<x:queryCreateRows from=“1” to=“10”>
<td><x:queryDisplay field=“ACCOUNT”/></td>
<td><x:queryDisplay field=“BALANCE”/></td>
</x:queryCreateRows>
</table>
</x:queryBlock>
</html>
30
Web Access
31
View Design Issues
32
Tasks in Web Layer
Request
Validation
Business Logic
Control
Presentation
33
Typical Tasks
• Validation of Input
– Client and server-side validation
– Is form data complete and well-formed?
• Interaction with Business Logic
– Create data
– Extract data for this user
• Controller
– What is the next step in conversation?
• Presentation of content
– Present data to client
34
View
Request Updates
Controller
Model
Customer
View
Selection
Display State Query
View
(read only)
JSP
Custom JSP Actions
JavaBeans Components
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
35
View: Response Generation
36
When Servlets, When JSP™
Technology Based Components?
37
How Do I Use All These Tools ?
MVC architecture.
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
38
View Design Guidelines
39
View Design Considerations
Design Considerations
– Servlet: for dispatching, control
between the Web tier and EJB
tier.
– JSP: benefit of separating
content and display logic, used
mainly for presentation
40
Java™ Programming Language Code (“Java
Code”) in the Page?
41
When to use JavaBeans vs EJBs
for Data Base Access?
• JSP->Controller Beans->EJB
(transactions: account, request)
– Container manages the connection pooling
and transactions
– Encapsulates the enterprise information
system resources and the core application
logic
– Scales well
• JSP->JavaBeans->DB (read-only, static
data, infrequent changes: catalog)
– High performance(No EJB overhead)
42
How they all work together
EJBs
Request
Forward
43
#A
Inventory
Entity Bean
update()
Manages data
main Controller
Servlet Session Bean
View Selection
doPost() purchaseItems()
Receives request Show Validates request
Validates input Confirmation Executes process OrderEJB
Calls session bean Page Enforces transactions
... Entity Bean
Calls JSP™ passing JSP
Value Model object Formats HTML create()
Responds to client Manages data
Question: why use a session bean? Why not execute from the servlet?
Answers:
Improves reuse to put all of the business logic in a component that can
be used by different types of clients
Improves network performance if servlets/EJBs are not co-located since
two (potentially large) entity objects don’t need to be referenced by the
client
44
#A
Example Servlet
IAccountHome accountHome;
IAccountBean account;
X
out.println(“<HTML><HEAD><TITLE>Your account</TITLE></HEAD>”);
out.println(“<BODY>Name “ + accountDetails.getName() + ”.<br>”);
out.println(“Address: “ + accountDetails.getAddress() );
•
•
•
}
Example code displays name, address for a customer. It utilizes an account EJB (entity bean)
public void doPost (HttpServletRequest req, HttpServletResponse res) {
String userId = req.getSession().getValue(“userId”);
IAccountHome accountHome;
IAccountBean account;
45
#A
Example JSP
JSPs are a presentation layer for Servlets...
<HTML>
<HEAD>
<TITLE>Your account</TITLE>
</HEAD>
<BODY>
<%
AccountDetails ad = (AccountDetails)
req.getAttribute(“account”, accountDetails);
%>
Name : <%=ad.getName()%> <br>
Address: <%=ad.getAddress()%> <br>
</BODY>
</HTML>
46
#A
IAccountHome accountHome;
IAccountBean account;
X
RequestDispatcher dispatcher;
out.println(“<BODY>Welcome “ + accountDetails.getName + ”.<br>”);
ServletContext context
out.println(“Address: “ +=getServletContext();
accountDetails.getAddress() );
•
Why do I ••dispatcher
care? = context.getRequestDispatcher(“estore/Account.jsp”);
req.setAttribute(“account”, accountDetails);
}
• Enables separation of presentation logic from presentation layout
dispatcher.forward(req, res);
• Enable your experts to play to their strengths
© Copyright 2000 Sun Microsystems, Inc., All rights reserved.
IAccountHome accountHome;
IAccountBean account;
47
Single Entry Point Controller
1. Parse Request
JSP
HTTP Page
Java Component
Requests (Entry (Central Controller)
Point)
ns
B ea
va
Ja
a re
P rep
2.
JSP
Java Bean
(Model)
Page
(View)
HTTP
Response
A single entry point to an application makes security,
application state, and presentation uniform and easier
to maintain.
In order to keep the java code separate from the content one can delegate this
task to a java bean.
48
Blueprints MVC Architecture
HTTP
Requests
First
Component
2
1 request
JSP™
Java Beans Enterprise
Page Components Beans
(View)
Model Data Model
Mirror Data
HTTP
Response
Web Tier EJB Tier
49
Resources
50