TECH854 XML TECHNOLOGIES Bringing XML to the Web Servlets and Web Applications - PowerPoint PPT Presentation

1 / 64
About This Presentation
Title:

TECH854 XML TECHNOLOGIES Bringing XML to the Web Servlets and Web Applications

Description:

TECH854. XML TECHNOLOGIES. Bringing XML to the Web. Servlets and Web Applications. Gillian Miller ... out.println(' body bgcolor=white ... – PowerPoint PPT presentation

Number of Views:129
Avg rating:3.0/5.0
Slides: 65
Provided by: gillian91
Category:

less

Transcript and Presenter's Notes

Title: TECH854 XML TECHNOLOGIES Bringing XML to the Web Servlets and Web Applications


1
TECH854XML TECHNOLOGIESBringing XML to the
WebServlets and Web Applications
  • Gillian Miller
  • gillian_at_ics.mq.edu.au
  • Week 7 2002/2

2
Bringing XML to Web
  • Web Servers and HTTP
  • Servlets
  • Forms and parameters
  • Sessions
  • Transferring control
  • Servlet errors
  • Obtaining a Web Server
  • Servlet Configurations
  • XSLT Transformations
  • XML Serialization
  • N-tiered applications
  • Advanced Framework - Using XSLT to separate
    logic, content and presentation

3

Browsers
Web Server

Servlet Engine
Internet
Servlet
IE
HTTP
DB Server XML files XSLT files
TCP/IP
Netscape
Clients, HTTP and Servers
4
HTTP Connection
  • Browser requests URL
  • Web Server sends HTTP response
  • HTTP Header, cookie ?, stream of text/html
  • Web Session
  • Client makes connection
  • Client requests document
  • Server Responds to request
  • Closes connection
  • Client CODE (browsers)
  • codeBrowser renders HTML to create visual page
  • HTML may contain program code (eg Javascript)
  • Browser user events - pass back to server
  • Click hyperlink to activate new URL
  • Open new URL in URL window
  • Form SUBMIT

5
Server Side
  • Server Side Processing
  • URLs may point to file or a program
  • Static HTML created from file system
  • OR program processes request and assembles HTML
    dynamically using server side processing
  • Result - Dynamically generated HTML
  • Recently, server does dynamic XML
  • Issues
  • HTTP is stateless so how to support complex
    application transactions
  • Process overheads on Web servers

6
Servlet Programming
  • Uses
  • Encapsulates HTTP
  • Process/store data from HTML Forms
  • Generate Dynamic Content
  • Web application Management
  • Our Context
  • Manage Web application generated using XML
  • Advantages over CGI
  • Efficient process model
  • Threads instead of OS Processes
  • Stays in memory between processes
  • Single Instance
  • Saves memory, allows management of persistent
    data
  • Convenience
  • High level utilities, packaging of session
    objects
  • Security, portability
  • Inexpensive

7
HTML lthtmlgtltbodygt lth1gtMy Malllt/h1gt lttablegtlttrgtlttd
gtProductlt/tdgt
XML lt?xml version1.0gt ltcatalog nameMy
Mallgt ltproductgt
Web Server
http
Web Browser
Servlet Engine
html
XML
XSLT
DataBase
  • Servlets encapuslate HTTP
  • Servlets read Client Data
  • (Forms, request headers)
  • Generate Results
  • Send Results back to client
  • (Headers, Status Results, HTML)

8
Java Servlet Framework
9
Servlets - Hello World 1
import java.io. import javax.servlet. import
javax.servlet.http. public class HelloWorld 1
extends HttpServlet public void
doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException PrintWriter
out response.getWriter()
out.println("Hello World 1")
imports
extend HttpServlet
doGet request response
http//localhost8080/servlet/HelloWorld1
10
Servlets - Hello World 2
public class HelloWorld2 extends HttpServlet
public void doGet(HttpServletRequest
request, HttpServletResponse response) throws
IOException, ServletException
response.setContentType("text/html") PrintWriter
out response.getWriter() out.println("lthtmlgt"
) out.println("ltheadgt") String title "Hello
World" out.println("lttitlegt" title
"lt/titlegt") out.println("lt/headgt") out.println
("ltbody bgcolorwhitegt") out.println("lth1gtltfont
color\"green\"gt" title "lt/fontgtlt/h1gt") Stri
ng param request.getParameter("param") if
(param ! null)
out.println("Thanks for the lovely param 'ltbgt"
param "lt/bgt'") out.println("lt/bodygt")o
ut.println("lt/htmlgt")
setContentType getWriter
req.getParameter (parmname)
11
Servlets
http//localhost8080/servlet/HelloWorld2?paramhe
llo
HttpServlet HelloWorld2 req.getParameter
(param)
servletURL?paramhelloworldviaurlspaces
12
You will need a Servlet Engine
  • Tomcat
  • Apache Tomcat - (part of Suns JSDK)
  • Quite complex in its deployment
  • Tomcat (as part of Netbeans)
  • Worked for me
  • See instructions in Resources
  • Jetty
  • Another lightweight server that worked for me
  • GO
  • Simple lightweight server (that worked for Jean
    Phillipe)
  • See resources
  • All of these programs require the servlet engine
    to be started
  • You may have to stop and restart servlet engine
    to force reloading of code
  • URLs will depend on engine and deployment
    configurations

http//localhost8080/servlet/servletname
13
Web Interactivity via Forms
  • FORMS
  • Enhanced HTML documents to collect information
  • Form inputs
  • text, password, radio, checkboxes, textareas,
    selection lists, option lists
  • Submit buttons
  • method Post (usual)
  • method Get
  • Web Server processes the form inputs then
    composes the reply
  • Servlets
  • Generate the Form HTML dynamically
  • Process the result using the DoPost method

14

15
(No Transcript)
16

lthtmlgtltheadgtlttitlegtSample Formlt/titlegtlt/headgt ltbod
ygt lth1gtDemonstration Formlt/h1gt ltform
actionmyservletURL" method"post"gt ltp
align"left"gtYour name (text box) ltinput
namefname type"text maxlength"32"
size"16"gt ltp align"left"gtSelect state
(Selection list) ltselect name"state" size"1"gt
ltoption value"NSW" selectedgt New South Wales
ltoption value"VIC"gtVictoria ltoption
value"QLD"gtQueenland ltoption value"SA"gtSouth
Australia lt/selectgt ltbrgt ltpgtComments ltbrgtlttextare
a name"comments" rows5 cols35gtlt/textareagt ltp
align"center"gtltinput type"submit"
name"feedback" value"Press to Submit
Details"gt lt/formgt lthr width"65"gtlt/bodygtlt/htmlgt

17
Read Sample Form
public class ReadSampleForm extends HttpServlet
public void doPost(HttpServletRequest
request,HttpServletResponse response) throws
IOException, ServletException response.setCont
entType("text/html") PrintWriter out
response.getWriter() String
title "Reading Sample Form"
out.println("ltHTMLgtltTITLEgt" title
"lt/TITLEgtlt/HEADgt") out.println(
"ltBODY BGCOLOR\"Yellow\"gt\n"
"ltH1 ALIGNCENTERgt" title "lt/H1gt\n"
" Thankyou for the following
informationltbrgt" "
ltBgtNamelt/Bgt "
request.getParameter("fname") "\n"
" ltBgtStatelt/Bgt "
request.getParameter("state") "\n"
" ltBgtCommentslt/Bgtltbrgt "
request.getParameter("comments") "\n"
"lt/BODYgtlt/HTMLgt")
use of doPost
request.getParameter
often use a doGet which calls doPost
18
Servlet LifeCycle
  • Service method
  • dispatches for different HTTP methods
  • doPost, doGet
  • doHead, DoDelete, DoTrace, DoOptions
  • use init method to initialise context, db
    connections
  • use destroy to clean up, close db connections

19
Issue
  • HTTP is stateless
  • Each doGet, doPost are single requests
  • HTTP does not keep track of clients
  • How to keep track of user state ?
  • eg shopping cart, accumulating information,
    saving re-entry of passwords etc
  • In CGI had to use cookies or fancy URLs or hidden
    fields in form
  • Servlets have high level functionality to deal
    with session information

20
HTTPSession
  • Session Object
  • unique for each client
  • Under hood maintained by Java using cookies or
    URL
  • Accessing the session object from HTTPRequest
  • HTTPSession session req.getSession(boolean
    create)
  • Testing the session object
  • if (session.IsNew())
  • if (session Null)
  • We can add and get objects from the session
    object
  • session.putValue (obj-name, myobject)
  • later
  • myobject session.getvalue(obj-name)

21
HelloSession
public class HelloSession extends HttpServlet
// Nested utility class private class
Tracker private int count
private Vector series public Tracker()
count 0 series new Vector()
public void upCount() count
public int getCount() return(count)
public void add(Object object)
series.addElement(object)
public void printSeries(PrintWriter out)
for (int i0 iltseries.size() i)
out.println(series.elementAt(i) " ")
public void doGet(
Use our own defined helper object called
Tracker upCount() add(object) getCount()
22
Tracker tracker null
HttpSession session request.getSession(false)
if (session null)
out.println("Hello there! I haven't seen you
before ..creating a session.")
session request.getSession(true)
tracker new Tracker()
session.putValue("tracker", tracker)
else tracker (Tracker)
session.getValue("tracker") //
At this point, a session and tracker object are
established // Increment the number of
visits and print the greeting
tracker.upCount() if (tracker.getCount()
1) out.println ("First serve ")
else out.println("Dang if we
haven't served you "
tracker.getCount() " times this session")

See if there is session
session.putValue (obj_key, object)
session.getValue (obj_key)
23
String page if (request.getParamet
er("gotob") ! null) doB(out)
page "b" else if (request.getParamet
er("gotoc") ! null) doC(out)
page "c" else
doA(out) page "a"
tracker.add(page) out.println("lthrgtOrder
of visits so far...") tracker.printSeries
(out) // Print the form with the A B C
buttons last doForm(out)
out.println("lt/bodygt") out.println("lt/html
gt") // Utility for form generation.
public void doForm(PrintWriter out)
out.println("lthrgtltformgtltinput namegotoa
typesubmit valueAgt")
out.println("ltinput namegotob typesubmit
valueBgt") out.println("ltinput
namegotoc typesubmit valueCgtlt/formgt")
public void doA(PrintWriter out)
out.println("lth2gtThe A page ruleslt/h2gt")
out.println("ltpgtThis is A grade stuff.")

form gotoa
use of tracker object
24
Session in action
example adapted from http//www-db.stanford.edu/u
llman/fcdb/oracle/or-web.html
25
Some Pieces
  • out.print "lt/HEADgtltBODYgtltFORM METHODPOST
    ACTION
  • out.print(response.encodeUrl(request.getRequestURI
    ()))
  • if (forminput null)
  • response.sendError(response.SC_BAD_REQUEST,
    you must enter input into form)

26
Inter Servlet Communication
public class FooServlet extends HttpServlet
protected void doGet(HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException ...
ServletContext context getServletConfig().getSer
vletContext() BarInterface bar
(BarInterface)context.getServlet("BarServlet")
bar.doBar() .. public interface
BarInterface public void dobar() public
class BarServlet extends HttpServlet implements
BarInterface public void dobar()
System.err.println("dobar() called"")

ServletContext (usually a directory) via
ServletConfig
Recast so that caller can use method of other
servlet
ref http//novocode.de/doc/servlet-essentials/cha
pter3.html
27
Forward to another Servlet
Dispatch request Forward
public class PresentationServlet extends
HttpServlet private static class
ItemNotFoundException extends Exception
ItemNotFoundException() super("Item not
found") protected void
doGet(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException
String item req.getParameter("item")
if(item null) req.setAttibute("ex
ception", new ItemNotFoundException())
getServletContext() .getRequestDispatcher("/servle
t/ErrorServlet") . forward(req,
res)
ref http//novocode.de/doc/servlet-essentials/cha
pter3.html
28
Including a response from another servlet
else // item was not null res.setContentType("
text/html") PrintWriter out res.getWriter()
out.print("ltHTMLgtltHEADgtltTITLEgtItem " item
"lt/TITLEgt" "lt/HEADgtltBODYgtItem " item
"ltPgt") getServletContext()
.getRequestDispatcher("/servlet/ItemServlet?item"
item) .include(req, res)
out.print("lt/BODYgtlt/HTMLgt")
Include
ref http//novocode.de/doc/servlet-essentials/cha
pter3.html
29
List Data Management
email1_at_usa.net santa_at_northpole
user 1
user 2
Multiple users writing via a servlet to some
shared resource (for this example we will use a
system file )
refhttp//novocode.de/doc/servlet-essentials/chap
ter2b.html
30
ListManagerServlet
import java.util.Vector import java.io.
import javax.servlet. import
javax.servlet.http. public class
ListManagerServlet extends HttpServlet
private Vector addresses private String
filename public void init(ServletConfig
config) throws ServletException
super.init(config) filename
config.getInitParameter("addressfile")
if(filename null) throw new
UnavailableException (this, "The
\"addressfile\" property must be set to a file
name") try ObjectInputStream in
new ObjectInputStream(new FileInputStream(filename
)) addresses (Vector)in.readObject()
in.close() catch(FileNotFoundException
e) addresses new Vector()
catch(Exception e) throw new
UnavailableException(this, "Error reading
address file "e)
use init to create application objects copy
address file into a vector
31
ListManagerServlet (contd)
private synchronized boolean subscribe(String
email) throws IOException if(addresses.contain
s(email)) return false addresses.addElement(ema
il) save() return true private
synchronized boolean unsubscribe(String email)
throws IOException if(!addresses.removeEle
ment(email)) return false save()
return true private void save() throws
IOException ObjectOutputStream out
new ObjectOutputStream(new FileOutputStream(file
name)) out.writeObject(addresses) out.close()

Utilities note use of synchronized (why?) After
each change save file (why?)
Your assignment (part b) will write XML files and
DOM !!
32
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
res.setContentType("text/html") PrintWriter
out res.getWriter() out.print("ltHTMLgtltHEADgt
ltTITLEgtList Managerlt/TITLEgtlt/HEADgt")
out.print("ltBODYgtltH3gtMemberslt/H3gtltULgt")
for(int i0 iltaddresses.size() i)
out.print("ltLIgt" addresses.elementAt(i))
out.print("lt/ULgtltHRgtltFORM METHODPOSTgt")
out.print("Enter your email address ltINPUT
TYPETEXT NAMEemailgtltBRgt")
out.print("ltINPUT TYPESUBMIT NAMEaction
VALUEsubscribegt") out.print("ltINPUT
TYPESUBMIT NAMEaction VALUEunsubscribegt")
out.print("lt/FORMgtlt/BODYgtlt/HTMLgt")
out.close()
33
protected void doPost(HttpServletRequest
req,HttpServletResponse res) throws
ServletException, IOException String
email req.getParameter("email") String
msg if(email null)
res.sendError(res.SC_BAD_REQUEST, "No email
address specified.") return
if(req.getParameter("action").equals("subscribe")
) if(subscribe(email)) msg "Address "
email " has been subscribed." else
res.sendError(res.SC_BAD_REQUEST,
"Address " email "already subscribed.") ret
urn
34
else if(unsubscribe(email)) msg
"Address " email " has been removed."
else res.sendError(res.SC_BAD_REQUEST,
"Address " email " was not
subscribed.") return
res.setContentType("text/html") PrintWriter
out res.getWriter() out.print("ltHTMLgtltHEADgt
ltTITLEgtList Managerlt/TITLEgtlt/HEADgtltBODYgt")
out.print(msg) out.print("ltHRgtltA HREF\"")
out.print(req.getRequestURI())
out.print("\"gtShow the listlt/Agtlt/BODYgtlt/HTMLgt")
out.close()
35
Back to XML
  • You have just created a Document Object Model
    (DOM) in your program
  • Serialization
  • Xerces has a XML serialization package
  • Recommended to use it to ensure correct handling
    of whitespace etc
  • Transforming XML via XSLT via Java
  • Java can transform XSLT to XML file
  • Java can also apply XSLT from one DOM to another

36
Serializing DOM
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.apache.xml.serialize.XMLSerializer
import org.apache.xml.serialize.OutputFor
mat
Maruyumo et al, p75
// Creates Document object via xerces
String documentImpl "org.apache.xerces.dom.Doc
umentImpl" Document doc
(Document)Class. forName(documentImpl).newInstanc
e() // Creates ltdepartmentgt element
as root Element root
doc.createElement("department") //
Sets the element as root
doc.appendChild(root)
// Now serialize
OutputFormat formatter new OutputFormat()
// Preserves whitespace
formatter.setPreserveSpace(true) //
The XML document is output to standard output
XMLSerializer serializer
new XMLSerializer(System.out,
formatter) // Serialize the DOM tree
as an XML document
serializer.serialize(doc)
37
Applying XSLT
XML and Java, Maruyumo et al, p 214 code
samples chap07/XSLTDomTest.java chap07/XSLTStreamT
est.java
  • Transformer class
  • TransformerFactory
  • javax.xml.transform.Transformer
  • javax.xml.transform.TransformerFactory
  • javax.xml.transform.stream.
  • javax.xml.transform.dom.
  • Can apply XSLT with
  • inputs either a DOM or Stream
  • DOMSource, StreamSource
  • outputs either a DOM or Stream
  • DOMResult, StreamResult

You may need to add Xalan libraries to your
classpath
38
XSLTStreamTest
Usage java XSLTStreamTest
filesample-1.xslt filesample.xml
import javax.xml.transform.TransformerFactory imp
ort javax.xml.transform.Transformer import
javax.xml.transform.stream.StreamSource import
javax.xml.transform.stream.StreamResult public
class XSLTStreamTest public static void
main(String args) throws Exception
String xsltURL args0 String xmlURL
args1 // Creates instances of
StreamSource for the stylesheet
StreamSource xslt new StreamSource(xsltURL)
// Creates instances of StreamSource for the
input document StreamSource xml new
StreamSource(xmlURL) // Creates an
instance of TransformerFactory
TransformerFactory factory
TransformerFactory.newInstance() //
Creates an instance of Transformer
Transformer transformer factory.newTransformer(x
slt) // Executes the Transformer
transformer.transform(xml, new StreamResult(System
.out))
39
JSP
  • Java Server Pages
  • Adds another layer on top of servlets
  • .jsp file extension
  • HTML code
  • fragments of Java code
  • Gets converted into servlet code
  • In practice need hybrid of JSP and servlets for
    more complex processing
  • Beyond scope of our requirements

40
Bringing it all together
  • Building a Web application
  • Series of screens, forms, lists to achieve
    functionality
  • eg assignment edit course unit, maintain
    selection list of course units
  • Most XML/ Java texts will have at least one
    chapter devoted to a complex Web servlet
    application
  • Choose one and study carefully to see how it all
    hangs together
  • Issues
  • Complexity of number of classes and functions
  • Sequencing of screens and user control
  • Synchronization of shared resources
  • Building in friendly error handling
  • Number of hardcoded print statements

41
Framework Design Issues
  • Three-Tier Architecture A common architecture
    for servlet based applications.
  • the application logic is implemented in a set of
    helper classes.
  • Methods on objects of these classes are invoked
    by the service methods in the servlets.
  • http//www.subrahmanyam.com/articles/servlets/Serv
    letIssues.html

42
The Presentation Nightmare
  • Java Servlets contain embedded HTML statements
    with presentation code everywhere
  • What happens if you want to redesign the look and
    feel of the site?
  • What happens if you want to be browser specific ?
    Work with PDAs?
  • A maintenance nightmare !!!!!
  • JSP only helps marginally

43
The case for XSLT
  • XSLT can be used to separate data, program, logic
    and presentation
  • XML and XSLT can be developed independently of
    servlet code
  • Modularity of presentation improves maintenance
  • Can target multiple client devices via different
    stylesheets
  • Weakness
  • adds layer of abstraction and extra step, slower
    runtime performance
  • Java and XSLT, Burke, OReilly chap 4, 6

44
XSLT
User Interface
Presentation Logic
Business Logic
Data
45
XSLT Conceptual Model
Servlet (controller)
request
HTML (view)
response
XSLT Processor
XML (Model)
XSLT Stylesheets (view)
46
Example
  • Detailed worked example
  • chapter 6 -Java and XSLT, Burke, OReilly
  • If you can use this in assignment (and get it
    working), this would qualify you for bonus marks
  • Sample code from books Web site (included in code
    for this week) for your detailed study.
  • Personal Data Entry XML file (sample.xml)
  • firstname, lastname, daytimephone etc
  • required attribute to indicate that field must be
    filled in
  • 2 XSLT stylesheets
  • EditPersonalData.xslt, ConfirmPersonalData.xslt
  • Source Code
  • PersonalDataServlet.java
  • PersonalData.java
  • PersonalDataXML.java

47
Sample.XML
lt?xml version"1.0" encoding"UTF-8"?gt lt?xml-style
sheet type"text/xsl" href"editPersonalData.xslt"
?gt ltpagegt ltrequiredFieldsMissing/gt
ltpersonalDatagt ltfirstName required"true"gtEric
lt/firstNamegt ltlastName required"true"gtBurkelt/
lastNamegt ltdaytimePhone required"true"gt636-12
3-4567lt/daytimePhonegt lteveningPhone/gt
ltemail required"true"gtburke_e_at_yahoo.comlt/emailgt
lt/personalDatagt lt/page
48
EditPersonalData.xslt
49
Form - EditPersonalData
sample.xml
EditPersonal Data.xslt
XSLT
result html
In fact I used XSLTStreamTest to run this
50
Sample ConfirmPersonalData
sample.xml
ConfirmPersonal Data.xslt
XSLT
result 2 html
51
PersonalData.java
Class PersonalData firstName, lastName
. isValid constructors getXXX setXXX
52
PersonalData.java (contd)
cleanup removes spaces
53
PersonalDataXML.java
Class PersonalDataXML produceDomDocument Separat
e DOM (the Model from rest of application)
54
PersonalDataXML.java (contd)
note utility addElem
55
PersonalDataServlet.java
import java.io. import java.net. import
javax.servlet. import javax.servlet.http. impo
rt javax.xml.transform. import
javax.xml.transform.dom. import
javax.xml.transform.stream. / A
demonstration Servlet that produces two pages. In
the first page, the user is prompted to enter
"personal information", including name, phone
number, and Email. In the second page, a summary
of this information is displayed. XSLT is used
for all HTML rendering, so this Servlet does
not enforce any particular look and feel.
/ public class PersonalDataServlet extends
HttpServlet private PersonalDataXML
personalDataXML new PersonalDataXML()
private Templates editTemplates private
Templates thanksTemplates
56
(continued)
public void init() throws UnavailableException
TransformerFactory transFact
TransformerFactory.newInstance() String
curName null try curName
"/WEB-INF/xslt/editPersonalData.xslt"
URL xsltURL getServletContext().getResource(c
urName) String xsltSystemID
xsltURL.toExternalForm()
this.editTemplates transFact.newTemplates(
new StreamSource(xsltSystemID))
curName "/WEB-INF/xslt/confirmPersonal
Data.xslt" xsltURL
getServletContext().getResource(curName)
xsltSystemID xsltURL.toExternalForm()
this.thanksTemplates transFact.newTemplat
es( new StreamSource(xsltSyste
mID)) catch (TransformerConfigurationEx
ception tce) log("Unable to compile
stylesheet", tce) throw new
UnavailableException("Unable to compile
stylesheet") catch (MalformedURLExcepti
on mue) log("Unable to locate XSLT
file " curName) throw new
UnavailableException( "Unable
to locate XSLT file " curName)
57
(continued)
PersonalData helper class Pass to helper
method to manage the session object !
/ Handles HTTP GET requests, such as
when the user types in a URL into his or
her browser or clicks on a hyperlink. /
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException, ServletException
PersonalData personalData getPersonalData(requ
est) // the third parameter, 'false',
indicates that error // messages should
not be displayed when showing the page.
showPage(response, personalData, false,
this.editTemplates)
Note use of showPage works via editTemplate
58
(continued)
Handles HTTP POST requests, user clicked
Submit / protected void doPost(HttpServletReq
uest request, HttpServletResponse
response) throws IOException,
ServletException // locate the
personal data object and update it with
// the information the user just submitted.
PersonalData pd getPersonalData(request)
pd.setFirstName(request.getParameter("firstNam
e")) pd.setLastName(request.getParameter(
"lastName")) pd.setDaytimePhone(request.g
etParameter("daytimePhone"))
pd.setEveningPhone(request.getParameter("eveningPh
one")) pd.setEmail(request.getParameter("
email")) if (!pd.isValid())
// show the 'Edit' page with an error message
showPage(response, pd, true,
this.editTemplates) else
// show a confirmation page
showPage(response, pd, false, this.thanksTemplates
)
Session Helper Object
Note use of showPage
59
(continued)
/ A helper method that sends the
personal data to the client browser as
HTML. It does this by applying an XSLT
stylesheet to the DOM tree. /
private void showPage(HttpServletResponse
response, PersonalData personalData,
boolean includeErrors, Templates
stylesheet) throws IOException, ServletException
try org.w3c.dom.Document
domDoc this.personalDataXML.
produceDOMDocument(
personalData, includeErrors)
Transformer trans stylesheet.newTransformer()
response.setContentType("text/html")
PrintWriter writer
response.getWriter()
trans.transform(new DOMSource(domDoc), new
StreamResult(writer)) catch (Exception
ex) showErrorPage(response, ex)

Utility showPage - applies XSLT
Helper App
60
(continued)
// common Error response private void
showErrorPage(HttpServletResponse response,
Throwable throwable) throws IOException
PrintWriter pw response.getWriter()
pw.println("lthtmlgtltbodygtlth1gtAn Error Has
Occurredlt/h1gtltpregt") throwable.printStack
Trace(pw) pw.println("lt/pregtlt/bodygtlt/html
gt") // A private helper to retrieve
session object private PersonalData
getPersonalData(HttpServletRequest request)
HttpSession session request.getSession(true)
PersonalData pd (PersonalData)
session.getAttribute(
"chap6.PersonalData") if (pd null)
pd new PersonalData()
session.setAttribute("chap6.PersonalData", pd)
return pd
61
Resources
  • Reference text XML and Java, 2e Maruyama et al
    - ch 10.2
  • JAVA and XSLT - OReilly, ch6, ch4, Burke
  • Java Sun Tutorial - servlets
  • http//java.sun.com/docs/books/tutorial/servlets/
  • http//java.sun.com/products/servlet/2.3/javadoc/
  • Novocode - Introduction to Servlets
  • http//novocode.de/doc/servlet-essentials/chapter1
    .html
  • (Note that some of this is deprecated code )

62
Marty Hall - Core Servlets
Marty Hall Course Slides online (first 4 or 5
chapters) and free Also text of Core Servlets and
JSP is online Tutorial - getting started with
Tomcat
http//courses.coreservlets.com/Course-Materials/
Intermediate-Course
63
CheckList - Understanding
  • Understand class paths, Java compilation,
    libaries
  • Use of IDE (eg NetBeans, JBuilder)
  • Download Xerces
  • DOM examples - Week 6
  • SAX examples - Week 5
  • Download Xalan
  • Transforming using XSLT from Java
  • Download a servlet engine - get helloWorld
    working
  • helloWorld, parameters, forms, session, data
    management
  • Study and understand a detailed XML and Web
    application
  • Apply to assignment - tackle in stages

64
Assignment 2
  • Plenty to absorb
  • Assignment 2 is out - tackle in stages
  • Get started with a servlet engine
  • Get SAX working (part 3 is independent)
  • Get DOM working
  • Get a form working
  • Get updates and adds working
  • Get this talking to a DOM - output to an XML file
  • Get a DOM list of units working
  • Add another page
  • Finesse with XSLT
Write a Comment
User Comments (0)
About PowerShow.com