Upload
waylon-breakey
View
222
Download
0
Tags:
Embed Size (px)
Citation preview
Introduction to Java Servlets
Rochester Java Users GroupJanuary 16th, 2002
Tom Bullinger
www.archwise.com
16Jan02 www.archwise.com Tom Bullinger
Agenda
HTTPWeb ArchitectureAppletsServletsSource / DemoReferences
16Jan02 www.archwise.com Tom Bullinger
ArchWise, LLC
A professional services firm specializing in software architecture. We provide
technical architecture solutions that are elegant as well as functional, and are
designed to meet the ongoing needs of the business as well as the marketplace.
We help our clients produce the right solution on time and on budget.
Member WWISA (http://www.wwisa.org)
16Jan02 www.archwise.com Tom Bullinger
ArchWise Software Architecture Map
Cover Story
BusinessArchitectur
e
Identity
VisionStatement
Goals Principles• To be the best…
• To provide …
• Our core …
• Partner with…
Architecture of Change
Results
Key Events
Projects
Organization Changes
Learnings
Key Hires
MarketArchitectur
e
TechnicalArchitectur
e
Execution
TestLogicalArch. Design
Code
Release
Market Map User Stories
Logical Architecture
Conceptual Architecture
UMLInterfacesUse Cases
Conceptual
Precise
Abstract
Meticulous
Start with: Business Plan
Start with:Architectureof Change
Start with:Conceptual Architecture
Start with:Logical Architecture
CRM
ERP
Supply Chain
Road Map
STAGES/TASKS
• Press Release
• Press Release
• Product Release
• Product Upgrade
MISSION
Q1 ‘02 Q2 ‘02
Stakeholder Profile
Context
Content Area
Menu
Brand
Tools/Status
BusinessGoals
SystemGoals
Magazine
Cover
Brain Storms
BusinessImage
Sidebars
QuotesHumanInterest
Lead Story
16Jan02 www.archwise.com Tom Bullinger
HTTP
Hypertext Transfer Protocol is: The primary protocol for Internet
communication Text based messages through sockets
Although payload may not be text Used to exchange resources
Files, video, audio, forms, graphics, etc. A Client / Server protocol (2-tier architecture)
Client opens a connection to a server Client sends a request message to the server Server sends a response message Server closes the connection
A stateless protocol Request Response
16Jan02 www.archwise.com Tom Bullinger
HTTP Request
Initial request line has 3 components: Method name Path to requested Resource HTTP version number
GET /web/index.html HTTP/1.0GET /web/index.html HTTP/1.0
16Jan02 www.archwise.com Tom Bullinger
HTTP Response
Initial response line (or status line) has 3 components: HTTP version number Response Status Code Reason Phrase
HTTP/1.0 404 Not FoundHTTP/1.0 404 Not Found
HTTP/1.0 200 OKHTTP/1.0 200 OK
HTTP/1.0 500 Server ErrorHTTP/1.0 500 Server Error
16Jan02 www.archwise.com Tom Bullinger
HTTP Headers
Headers are mostly optional, and include supporting information for the request or response messagesConsists of 2 parts: Header name Value
From: [email protected]: Mozilla/3.0Gold
From: [email protected]: Mozilla/3.0Gold
(Request)
Server: Apache/1.2b3-devLast-Modified: Fri, 31 Dec 1999 23:59:59 GMTContent-type: text/htmlContent-length: 47
Server: Apache/1.2b3-devLast-Modified: Fri, 31 Dec 1999 23:59:59 GMTContent-type: text/htmlContent-length: 47
(Response)
16Jan02 www.archwise.com Tom Bullinger
HTTP ExampleGET /path/file.html HTTP/1.0From: [email protected]: Mozilla/3.0Gold[blank line]
GET /path/file.html HTTP/1.0From: [email protected]: Mozilla/3.0Gold[blank line]
(Request)
HTTP/1.0 200 OKDate: Fri, 31 Dec 1999 23:59:59 GMTContent-Type: text/htmlContent-Length: 1354
<html> <body> <h1>Use Servlets!</h1> . . </body></html>[blank line]
HTTP/1.0 200 OKDate: Fri, 31 Dec 1999 23:59:59 GMTContent-Type: text/htmlContent-Length: 1354
<html> <body> <h1>Use Servlets!</h1> . . </body></html>[blank line]
(Response)
16Jan02 www.archwise.com Tom Bullinger
HTTP Methods
GET Requests a resource from the server Data is URL-encoded and appended to URL
HEAD Like GET, but returns the header only, not
the resource
POST Like GET, but data is URL-encoded in
message body Extra header lines Message body (data)
Typically a script or program invocation Response is typically created dynamically
16Jan02 www.archwise.com Tom Bullinger
URL Encoded Data (Key/Value)
HTML form data is usually URL-encoded to package it in a GET or POST submission. In a nutshell, here's how you URL-encode the name-value:
1. Convert all "unsafe" characters in the names and values to
"%xx", where "xx" is the ascii value of the character, in hex.
"Unsafe" characters include =, &, %, +, non-printable
characters, and any others you want to encode
2. Change all spaces to plusses.
3. String the names and values together with = and &
name1=value1&name2=value2&name3=value3name1=value1&name2=value2&name3=value3
16Jan02 www.archwise.com Tom Bullinger
Web Browser Architecture
Client(browser)
User
Server(web server) File
s
16Jan02 www.archwise.com Tom Bullinger
Typical Interaction:Browser
User
:Server HTML:File
URLGET URL HTTP/1.0 Decode(URL)
Read()HTTP/1.0 200 OK…
Display(HTML)
16Jan02 www.archwise.com Tom Bullinger
Problems?
Where is the work done?
Is this scalable?
Is this flexible?
What about dynamic content?
16Jan02 www.archwise.com Tom Bullinger
Applets
Extends Browser capabilityImplemented in JavaDownloaded from server to clientInterpreted by Browser (or plug-in)Embedded in static web pages (HTML)Provides rich visual functionalityLimited capability on the local machine Cannot access file system Cannot access non-home IP addresses Cannot access underlying OS
16Jan02 www.archwise.com Tom Bullinger
Applet Architecture
Client(browser)
User
Server(web server)File
s
Client(applet)
CustomBackend File
s
16Jan02 www.archwise.com Tom Bullinger
Typical Interaction:Browser
User
:Server HTML:File
URLGET URL HTTP/1.0 decode(URL)
:Applet
read(…)
read(…)
HTML
Applet
init()
start()paint()
16Jan02 www.archwise.com Tom Bullinger
Applet Limitations
No persistence mechanism
Client-side implementation
Requires custom backend for server-side
Practical limit to size (due to download)
Limited functionality on client(Actually limited by security manager, could
be replaced if desired)
Others?
16Jan02 www.archwise.com Tom Bullinger
Servlets
Implemented in JavaExtends the request / response capability of the serverHandles client HTTP requestsNo user interface componentCompatible with many serversServer / container manages lifecycleMay be reentrant
16Jan02 www.archwise.com Tom Bullinger
Lineage of a Servlet
Servlet
Generic Servlet
HttpServlet
Custom Servlet
(Interface)
(Abstract base class)
(Default implementation)
(user-supplied behavior)
16Jan02 www.archwise.com Tom Bullinger
Methods of interest
doGet - implements HTTP GET requests
doPost - implements HTTP POST requests
doPut - implements HTTP PUT requests
doDelete - for HTTP DELETE requests
init and destroy - manage resources that are held for the life of the servlet
getServletInfo - provides information about the servlet
16Jan02 www.archwise.com Tom Bullinger
Other Methods
service - Server entry point, dispatches
to doXXX methods
doTrace - implements HTTP TRACE
requests
doOptions - implements HTTP OPTIONS
requests
16Jan02 www.archwise.com Tom Bullinger
Servlet Data interface
Two interfaces are utilized in the client / servlet relationship: ServletRequest - encapsulates
communication from the client to the server ServletResponse - encapsulates
communication from the servlet back to the client
Instances provided by the frameworkServletRequest
HttpServletRequest
ServletResponse
HttpServletResponse
16Jan02 www.archwise.com Tom Bullinger
A Simple Servletpublic class SimpleServlet extends HttpServlet{ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output";
// set content type and other response header fields first response.setContentType("text/html");
// then write the data of the response out = response.getWriter();
out.println("<HTML><HEAD><TITLE>"); out.println(title); out.println("</TITLE></HEAD><BODY>"); out.println("<H1>" + title + "</H1>"); out.println("<P>This is output from SimpleServlet."); out.println("</BODY></HTML>"); out.close(); }}
16Jan02 www.archwise.com Tom Bullinger
Servlet Architecture
Client(browser)
User
Server(web server) File
s
ServletFiles
16Jan02 www.archwise.com Tom Bullinger
Typical Interaction:Browser
User
:Server :Servlet
URLGET URL HTTP/1.0 decode(URL)
HTTP/1.0 200 OK…
Display(HTML)
service(rq, rs)
rq:Request rs:Response
doGet(rq, rs)
write(…)
Behaviorgoes here
16Jan02 www.archwise.com Tom Bullinger
Handling requests from the Client
HttpServletRequest Encapsulates the data provided by the client Provides several methods for accessing the data:
getParameter(String name) - returns the value of the specified parameter
getParameterValues(String name) - returns an array of strings of parameter values
getParameterNames( ) - returns an enumeration of names
getQueryString( ) - provide raw data from a GET request getReader( ) - for reading raw text data from the request getInputStream( ) - for reading raw binary data from the
request
16Jan02 www.archwise.com Tom Bullinger
Responding to Clients
HttpServletResponse Encapsulates the data provided to the client Provides several methods for setting the
data: setContentType(String type) - sets the header
value for content type
getWriter( ) - provides a Writer for adding data to the response
getOutputStream( ) - for writing raw binary data to the response
16Jan02 www.archwise.com Tom Bullinger
doGet and doPost Pattern
Read input data from the Request objectGet the output writer from the Response objectSetup the header dataPerform the necessary processing Database access Calculations Input/Output
Write the HTML to the response object
16Jan02 www.archwise.com Tom Bullinger
Source Template public void doGet/doPost (HttpServletRequest request, HttpServletResponse response) …{ // set content-type header before accessing the Writer response.setContentType("text/html"); // get the writer PrintWriter out = response.getWriter();
// extract data from the request String name = request.getParameter(“FirstName");
// perform required processing … // write the output to the writer (in HTML) … // cleanup out.close();}
16Jan02 www.archwise.com Tom Bullinger
Lifecycle of a servlet
The container: Creates and initializes the Servlet Handles zero or more servic calls from clients Destroys the Servlet and garbage collects it
Servlets persist between service calls Memory footprint is reduced Dynamic resources are held open
database handles Socket connections
Lifecycle overhead is eliminated Each client gets a thread
16Jan02 www.archwise.com Tom Bullinger
When should you use a servlet?
For dynamic web content Allows easy connection to database for
persistence mechanism
For stateful protocols Servlet session maintains state
For server performance Servlets are loaded once, reentrant
thereafter
For embedded web servers Web-enabled appliances
16Jan02 www.archwise.com Tom Bullinger
Advantages of Servlets
Portability - “write once, serve anywhere” Unlike applets, only need to be tested on the server No complex GUI
Power Full power of Java is available
JDBC RMI J2EE CORBA Bridge EJB JTS JMS JNDI
Support for third-party tools
16Jan02 www.archwise.com Tom Bullinger
More Advantages
Efficiency Once loaded, remains loaded Multiple concurrent requests handled by
threads Maintains state across invocations (if
appropriate)
Safety Java type-safety Java memory management Java exception handling Java security manager
16Jan02 www.archwise.com Tom Bullinger
More Advantages
Elegance Clean, object-oriented, modular code Base classes provide routine functionality
Programming by difference
Integration As a server extension, leverages server
capability File paths Logging Authorization MIME type mapping
Session tracking Overlays state on HTTP protocol
16Jan02 www.archwise.com Tom Bullinger
More Advantages
Extensible Built-in support for HTTP Servlets Others can be created Can create HTML Can work with XML / XSLT
16Jan02 www.archwise.com Tom Bullinger
Deploying Servlets
In HTML Specify servlet URL in ACTION tag
Specify servlet URL in HREF tag
Specify servlet URL directly
16Jan02 www.archwise.com Tom Bullinger
Servlet Containers
Tomcat Standalone HTTP / servlet container HTTP server extension / servlet container
J2EE Servlet container EJB container JMS JNDI JTA JAXP JDBC Etc.
16Jan02 www.archwise.com Tom Bullinger
Demo / Examples
Let’s look at some running Servlets
16Jan02 www.archwise.com Tom Bullinger
References
Java Servlet Programming - Jason Hunter with
William Crawford Copyright 2001, 1998 O’Reilly & Associates
The Internet Big Picture - Russ Haynal http://navigators.com/internet_architecture.html
http://www.jmarshall.com/easy/http/
http://java.sun.com/docs/books/tutorial/
servlets/