XML Parsing - SAX
1
Parsing and Application ●
Parsing – –
●
Well-formed’ness checking & Validating Reading
Application – – –
Manipulating Creating Writing and Sending
2
SAX Historical Background ● ●
Simple API for XML Started as community-driven project –
●
Originally designed as Java API –
●
xml-dev mailing list Others (C++, Python, Perl) are now supported
SAX 2 –
Namespaces
3
SAX Features
Event-driven –
Fast and lightweight –
● ● ●
You provide event handlers Document does not have to be entirely in memory
Sequential read access only One-time access Does not support modification of document
4
SAX Operational Model
Events
Input XML Document
Parser
Provided Handler
5
SAX Programming ●
Collection of Java interfaces and classes
●
org.xml.sax package
Interfaces –
Parser ●
–
XMLReader
Event handlers ●
ContentHandler
6
SAX Programming Procedures Create XML Parser
Create Event Handler
Call Parser and Set Event Handler
Parse Handling
Event Handler Processing
XMLReader parser = XMLReaderFactory.createXMLReader();
myHandler handler = new myHandler();
parser.parse(args[0]);
SAX parser calls methods on the event handler
public void startDocument(){ System.out.println(“XML Document Start”); }
7
XMLReader Interface ●
Represents SAX parser –
●
SAX2 parser implementation has to implement this interface
Methods for – – –
Registering event handlers Initiating parsing Configuring features and properties ●
Validation on and off
8
XMLReader Interface public interface XMLReader{ public boolean getFeature (String name) throws SAXNotRecognizedException, SAXNotSupportedException; public void setFeature (String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException; public Object getProperty (String name) throws SAXNotRecognizedException, SAXNotSupportedException; public void setProperty (String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException; public void setEntityResolver (EntityResolver resolver); public EntityResolver getEntityResolver (); public void setDTDHandler (DTDHandler handler); public DTDHandler getDTDHandler (); public void setContentHandler (ContentHandler handler); public ContentHandler getContentHandler (); public void setErrorHandler (ErrorHandler handler); public ErrorHandler getErrorHandler (); public void parse (InputSource input) throws IOException, SAXException; public void parse (String systemId) throws IOException, SAXException; }
9
XMLReader Instance ●
● ●
Concrete implementation instance “bound” to XMLReader interface Has to be created before parsing Gets created by using static method of createXMLReader() method of helper class XMLReaderFactory
10
XMLReader Example XMLReader parser = null; try { // Get SAX parser instance reading org.xml.sax.driver // system property. parser = XMLReaderFactory.createXMLReader(); // Parse the document }catch(SAXException ex){ // Couldn’t create XMLReader // either because org.xml.sax.driver system property // was not set or set incorrectly. }
11
Setting Features ●
●
setFeature(String, boolean) method of XMLReader interface Features – – –
General features SAX features DOM features
12
Features ●
General Features – – – –
●
http://xml.org/sax/features/validation http://xml.org/sax/features/namespaces http://apache.org/xml/features/validation/schema http://apache.org/xml/features/continue-after-fatal-error
SAX Features –
http://xml.org/sax/features/namespace-prefixes
13
Example XMLReader parser = null; try { // Create an instance of Apache’s Crimson SAX parser parser = XMLReaderFactory.createXMLReader(); // Set features parser.setFeature("http://xml.org/sax/features/validation", true); // Parse the document }catch(SAXException ex){ }
14
Parse Methods ● ●
void parse(String uri) throws SAXException, IOException void parse(InputSource source) throws SAXException, IOException
15
XMLReader parser = null; try { parser = XMLReaderFactory.createXMLReader();
Example
// Parse the document parser.parse(“http://www.slashdot.org/slashdot.xml”); // Capture SAX events }catch(SAXException ex){ // exception occurs maybe because document // is malformed }
16
XMLReader parser = null; try { parser = XMLReaderFactory.createXMLReader();
Example
// Parse the document in File URI form parser.parse(“file:/tmp/people.xml”); // Capture SAX events }catch(SAXException ex){ // exception occurs maybe because document // is malformed }
17
InputSource Objects ●
● ●
Encapsulates information about an input source as a single object Passed to the XMLReader.parse() method May include the following: – – – –
Public identifier System identifier A byte stream A character stream
18
Parser Behavior on InputSource ●
●
●
If character stream is available, parser will read that stream directly Else if byte stream is available, parser will read byte stream Else open URI connection to resource specified in System identifier
19
SAX Event Handlers ●
Interfaces – – – – –
●
ContentHandler ErrorHandler DTDHandler EntityResolver Attributes
Class –
DefaultHandler
20
SAX Event Handlers <
> ContentHandler
<> Implements
DefaultHandler
ErrorHandler
<> DTDHandler
<> EntityResolver
21
ContentHandler Interface public interface ContentHandler{ void startDocument () throws SAXException; void endDocument() throws SAXException; void startElement(String namespace, String name, String qName, Attributes atts) throws SAXException; void endElement(String namespace, String name, String qName) throws SAXException; void characters(char [ ] ch, int start, int length) throws SAXException; void ignorableWhiteSpace(char [ ]ch, int start, int length) throws SAXException; void processingInstruction(String target, String data) throws SAXException; void setDocumentLocator(Locator locator); void startPrefixMapping(String prefix, String uri) throws SAXException; void endPrefixMapping(String prefix) throws SAXException; void skippedEntity(String name) throws SAXException; } 22
Simple SAX Example: Parser XMLReader parser = null; try { // Create XML (non-validating) parser parser = XMLReaderFactory.createXMLReader(); // Create event handler myContentHandler handler = new myContentHandler(); parser.setContentHandler(handler); // Call parsing method parser.parse(args[0]); }catch(SAXException ex){ System.err.println(ex.getMessage()); }catch(Exception ex){ System.err.println(ex.getMessage()); }
23
Simple SAX Example: Event Handler class myContentHandler implements ContentHandler { // ContentHandler methods public void startDocument(){ System.out.println(“XML Document START”); } public void endDocument(){ System.out.println(“XML Document END”); } public void startElement(String namespace, String name, String qName, Attributes atts){ System.out.println(“<“ + qName + “>”); } public void endElement(String namespace, String name, String qName){ System.out.println(“); } public void characters(char[] chars, int start, int length){ System.out.println(new String(chars, start, length); } 24
Character Data ●
●
●
Character data – void characters(char [ ] ch, int start, int length) throws SAXException Parsers are allowed to break up character data any way desired Character data are in Unicode regardless of encoding scheme specified in XML document
25
White Space ●
White space – Nonvalidating parser ●
–
Validating parser ●
●
void characters(char [ ] ch, int start, int length) throws SAXException void ignorableWhiteSpace(char [ ]ch, int start, int length) throws SAXException
“Ignorable white space” includes spaces, tabs and newlines
26
Attributes Interface public interface Attributes{ public abstract int getLength(); public abstract int getIndex(String qName); public abstract int getIndex(String namespace, String name) public abstract String getLocalName(int index) public abstract String getQName(int index) public abstract String getType(int index) public abstract String getType(String qName) public abstract String getType(String namespace, String name) public abstract String getValue(String qName) public abstract String getValue(String namespace, String name) public abstract String getValue(int index) public abstract String getURI(int index) }
27
Locator Interface ●
Tells application where events occurred
public interface Locator{ public int getLineNumber(); public int getColumnNumber(); public String getPublicId(); public String getSystemId(); }
28
Locator Interface ●
SAX parser passes implementation instance of Locator interface to the
ContentHandler.setDocumentLocator() –
It should be saved to a local reference if the application needs it
29
Locator Example Locator loc; public void setDocumentLocator(Locator loc){ this.loc = loc; } public void startElement(String namespace, String name, String qName, Attributes a){ System.out.println(name); System.out.println(“ line: “ + loc.getLineNumber()); System.out.println(“ ID: “ + loc.getSystemId()); }
30
ErrorHandler Interface public interface ErrorHandler{ void error(SAXParserException e) throws SAXException void fatalError(SAXParseException e) throws SAXException void warning(SAXParseException e) throws SAXException }
31
DTDHandler Methods Public interface DTDHandler{ void notationDecl(String name, String publicID, String systemID) throws SAXException void unparsedEntityDecl(String name, String publicID, String systemID, String notationName) throws SAXException }
32
EntityResolver Interface Public interface EntityResolver{ InputSource resolveEntity(String publicID, String systemID) throws SAXException } ●
●
This method is used to return an InputSource so the content of the external entity can be read An external entity – –
External Parsed Entities Unparsed Entities
33
DefaultHandler Class ● ●
Helper class Implements
●
●
ContentHandler ErrorHandler DTDHandler EntityResolver
Just subclass and override the methods you are interested in. Completely optional for use
34
JAXP/SAX Code Sample 01 02 03 04 05 06 07 08 09 10 11 12 13 14
import javax.xml.parsers.*; import org.xml.sax.*; SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); // can also parse InputStreams, Files, and // SAX input sources parser.parse("http://foo.com/bar.xml", mySAXEventHandler); ..
35
Benefits Of SAX ● ● ●
●
●
It is very simple It is very fast Useful when custom data structures are needed to model the XML document Can parse files of any size without impacting memory usage Can be used to gather a subset of a document’s information
36
Drawbacks Of SAX ● ● ●
SAX provides read-only access No random access to documents Searching of documents is not easy
37
DOM (Document Object Model)
38
Historical Background ● ●
●
DOM is a standard defined by the W3C, just like XML DOM was not designed specifically for Java technology (unlike SAX) DOM is cross-platform and cross-language – –
Uses OMG’s IDL to define interfaces IDL to language binding
39
DOM Characteristics ●
● ● ●
Access XML document as a tree structure Composed of mostly element nodes and text nodes Can “walk” the tree back and forth Larger memory requirements –
●
Fairly heavyweight to load and store
Use it when for walking and modifying the tree
40
DOM in Action
Creates Tree
Input XML Document
Parser
41
DOM Tree and Nodes ● ● ● ●
XML document is represented as a tree A tree is made of nodes There are 12 different node types Nodes may contain other nodes (depending on node types) –
parent node contains child nodes
42
Node Types ●
● ● ● ● ● ● ●
Document node Document Fragment node Element node Attribute node Text node Comment node Processing instruction node Document type node Entity node Entity reference node CDATA section node Notation node 43
JDOM – a DOM API for Java ●
●
●
●
JDOM is an open source API designed to represent an XML document and its contents to the typical Java developer in an intuitive and straightforward way. Java optimized. It behaves like Java, it uses Java collections, and it provides a low-cost entry point for using XML. JDOM users don't need to have tremendous expertise in XML to be productive and get their jobs done. JDOM interoperates well with existing standards such as the Simple API for XML (SAX) and the Document Object Model (DOM).
44
Java EE
45
Alapfogalmak ●
●
Java = –
Objektumorientált programozási nyelv
–
Hordozható byte code
–
A byte code-ot futtató virtuális gép (jvm)
–
Standard API-k gyűjteménye
A Java platform kiadásai –
Micro Edition (Java ME) ●
–
Standard Edition (Java SE) ●
–
Mobiltelefonok, set-top-box-ok, PDA-k
Egy felhasználó elé kerülő desktop alkalmazások fejlesztése
Enterprise Edition (Java EE) ●
Vállalati szintű, többrétegű, sokfelhasználós alkalmazások 46
A Java EE platform alapgondolata A platform felelőssége
Konkurrencia Biztonság Rendelkezésre állás Skálázhatóság Perzisztencia Tranzakciók Életciklus menedzsment Felügyelet
A fejlesztő felelőssége
A prezentációs logika Az üzleti logika (A teszt logika) Ismerni a platform nyújtotta összes szolgáltatást :-)
47
Miért Java EE? ●
Szabvány –
A platformfüggetlen Java SE környezetre épülő API-k és konténerek összessége
–
A gyártók együttműködnek a specifikációk készítésénél és többnyire csak az implementációk minősége, szolgáltatásai terén versenyeznek ●
●
●
A sokezer USD/CPU-s terméktől a nyílt forrású Java EE kiszolgálóig széles a termékek palettája A fejlesztők szabadon választhatnak a Java EE szabvány adott verzióját implementáló futtatókörnyezetek között
Java EE kompatibilitás –
Alkalmazás hordozhatóság gyártói platformok között
48
Java EE 5 ●
●
A Java Standard Edition (leánykorában J2SE) 5-ös változata jelentős nyelvi változásokat hozott a Java világba –
Generikus típusok (ami nagyon más, mint a C++ template-ek)
–
Annotációk (címkék a kódban, melyek belefordulnak a byte code-ba és dinamikusan felderíthetőek futás közben)
Az annotációk segítségével a Java EE fejlesztés jelentősen egyszerűsödik –
XML alapú deployment descriptor-ok helyett a .java forrásba írt annotációk írják le a fejlesztett komponens és a kiszolgáló által nyújtott konténer közötti kapcsolatot
49
Java EE API-k
50
●
Gyakran használt Java EE API-k Java Message Service – üzenetek küldése/fogadása
●
Java Transaction API
●
JavaMail API – e-mail üzenetek kezelése
●
Java API for XML Web Services
●
Java Architecture for XML Binding
●
SOAP with Attachments API
●
J2EE Connector Architecture
●
Java Naming and Directory Interface
●
Java Authentication and Authorization Service
51
Java EE rétegek
52
Java EE konténerek
53
Java EE konténerek ●
●
●
Web konténer –
A HTTP kérések kiszolgálását végző Java EE komponens
–
Feladatkör: webalkalmazások, webszolgáltatások kezelése
EJB konténer –
Az Enterprise JavaBean technológiát alkalmazó komponensek futtatására képes Java EE komponens
–
Feladatkör: üzleti logika, objektum perzisztencia, üzenetküldés, kapcsolódás EIS rendszerekhez
Application client container –
Az alkalmazásszervert elérő, a kliensen futó standalone Java alkalmazások futtatási környezete
54
Konténerek szolgáltatásai ●
Komponensek és erőforrások felderítése –
●
●
JNDI API
Komponensek életciklusának menedzselése –
Alkalmazások, modulok telepítése (deploy), törlése (undeploy)
–
Alkalmazások elindítása, megállítása
Egyebek –
Monitoring (JMX)
–
Naplózás (java.util.logging)
55
Alkalmazáscsomagok ●
●
Standard könyvtárstruktúrák –
.ear (enterprise archive)
–
.war (web archive)
–
.rar (resource archive)
Standard és gyártófüggő alkalmazásleírók (deployment descriptor) –
application.xml
–
web.xml
–
ejb-jar.xml
56
Perzisztencia ●
●
●
Egy objektum által tárolt információ elmentése valamilyen háttértárba Sok lehetséges megoldása létezik a problémának –
Objektumszerializáció
–
XML szerializáció (JAXB)
–
Objektum-relációs leképezés (ORM) ●
Korábbi szabványok (EJB 2.1 Entity Beans, JDO)
●
Open source framework-ök tömkelege (pl Hibernate, Torque)
●
Kereskedelmi szoftverek (pl Toplink)
Java EE 5: Java Persistence API –
Az egyre népszerűbb, open source framework-ök által megcélzott útvonal beemelése a Java EE szabványokba
57
Java Persistence API ●
●
●
●
Könnyebb fejlesztés és deployment az előd EJB Entity API-hoz képest A perzisztálandó objektumok között öröklődési kapcsolat lehet, polimorfizmus megengedett Használható Java EE konténereken kívül is (nem kell hozzá alkalmazásszerver – könnyíti a unit testinget is) Az entitások egyszerű, megfelelően annotált Java osztályok
58
Java Persistence API @Entity public class Customer { private Long id; private String name; private Address address; private Collection orders = new HashSet(); public Customer() {} @Id public Long getID() { return id; } protected void setID (Long id) { this.id = id; } 59
Java Persistence API // Relationship between Customer and Orders @OneToMany public Collection getOrders() { return orders; } public void setOrders(Collection orders) { this.orders = orders; }
60
Entity használata @Stateless public class OrderEntry { // Dependency injection of Entity Manager for // the given persistence unit @PersistenceContext EntityManager em; public void enterOrder(int custID, Order newOrder){ // Use find method to locate customer entity Customer c = em.find(Customer.class, custID); // Add a new order to the Orders c.getOrders().add(newOrder); newOrder.setCustomer(c); } } 61
A JPA Entity-k életciklusa
62
Az üzleti logika rétege ●
Java EE módon: –
●
EJB 3.0
Lightweight módon: –
A web rétegben egyszerű Java osztályokban ●
–
A programozó felelőssége ezek életciklusának felügyelete, tranzakciók kezelése, jogosultságvizsgálatok lefolytatása, stb
Spring ●
●
Az Inversion of Control és a Dependency Injection tervezési mintákat implementáló, J2EE környezetben, vagy anélkül is használható keretrendszer XML konfigurációs file-ok alapján konfigurált alkalmazások
63
EJB 3.0 ●
Enterprise JavaBeans –
Maguk az üzleti logikát implementáló osztályok
–
Két típusa létezik
–
●
Session Bean-ek (stateless/stateful)
●
Message Driven Bean
A konténer gondoskodik az erőforrások eléréséről, a szálkezelésről (az EJB-k thread safe objektumok), az authorizációról, a tranzakciókról (akár XA, two phase commit), stb – ennek konfigurációja annotációkkal történik:
@MessageDriven(mappedName="jms/Queue") public class SimpleMessageBean implements MessageListener { @Resource private MessageDrivenContext mdc;
64
Session Bean ●
Session Bean interfész –
Local vagy Remote elérés
@Remote public interface Converter { public BigDecimal dollarToYen(BigDecimal dollars); public BigDecimal yenToEuro(BigDecimal yen); } ●
Session Bean osztály –
POJO, ami az interfészt implementálja
@Stateless public class ConverterBean implements Converter { public BigDecimal dollarToYen(BigDecimal dollars) { BigDecimal result = dollars.multiply(yenRate); return result.setScale(2, BigDecimal.ROUND_UP);
}
65
A Session Bean-t használó kliens
public class ConverterClient { @EJB
private static Converter converter; public ConverterClient(String[] args) { } public static void main(String[] args) { ConverterClient client = new ConverterClient(args); client.doConversion(); } public void doConversion() { try { BigDecimal param = new BigDecimal("100.00"); BigDecimal yenAmount = converter.dollarToYen(param);
66
Session Bean ●
Egyetlen kliens session-jét reprezentáló objektum
●
Két típusa van: –
Állapotmentes (Stateless) ●
●
●
–
A bean esetleges attribútumai nem őriződnek meg a kliens két hívása között Az állapotmentesség miatt jobban skálázható a stateless session bean-eket használó alkalmazás Csak állapotmentes session bean lehet webszolgáltatás végpont
Állapottal rendelkező (Stateful) ●
●
Két hívás között, a kliens és a bean közötti kapcsolat lezáródásáig megörződik a bean állapota, attribútumainak értéke Bizonyos körülmények között a konténer kiíhatja az állapotot valamilyen háttértárba (passziválás)
67
Webes keretrendszerek ●
Az alapok: a Servlet API, JSP, MVC
●
Kérés-válasz alapú keretrendszerek –
●
Struts
Komponens alapú keretrendszerek –
JSF
–
Wicket
68
Az alapok: a Servlet API, JSP, MVC
Web Tier
EJB Tier
69
A Servlet ●
●
Java objektum, ami a servlet keretrendszert és API-t használja és egy HTTP kiszolgáló funkcionalitását bővíti Nagyon sikeres API (gyakorlatilag minden más web framework erre épül)
public class HelloServlet extends HttpServlet {
}
public void doGet(HttpServletRequest request, HttpServletResponse response){ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Hello World!"); } ... 70
Servlet életciklus service( )
init( )
destroy( ) Ready
Init parameters
doGet( )
doPost( )
Request parameters 71
Webalkalmazások (.war) struktúrája
72
CGI modell vs Servlet modell CGI
Bármely nyelven írható Nehezen skálázható, felügyelhető Gyakori biztonsági hibák Pazarlóan bánik az erőforrásokkal (fork()) Platform és alkalmazás specifikus
Servlet
Java objektum Erős, megbízható és hatékony Skálázható, újrahasznosítható A Java beépített biztonsági modelljét használja Platformfüggetlen
73
CGI modell vs Servlet modell Request Request CGI1 CGI1 Request Request CGI2 CGI2 Request Request CGI1 CGI1 Request Request Servlet1 Servlet1 Request Request Servlet2 Servlet2 Request Servlet1
Child Childfor for CGI1 CGI1
CGI CGI Based Based Webserver Webserver
Child Childfor for CGI2 CGI2 Child Childfor for CGI1 CGI1
Servlet Servlet Based Based Webserver Webserver JVM JVM
Servlet1 Servlet1 Servlet2 Servlet2
74
A Servletek tulajdonságai ● ●
●
●
●
Többszálú végrehajtás egyetlen objektumon Beépített HTTP session kezelés (cookie vagy GET paraméter alapon) Beépített (container managed) authentikáció (basic, form, digest, cert) ContextListener-eken keresztül a kérések, session kezelése több ponton befolyásolható A web container újraindítás nélkül képes a web alkalmazások életciklusát kezelni 75
Objektumok láthatósága ●
Web context (ServletConext) ●
●
Session ●
●
Egyazon webalkalmazásban lévő összes servlet összes kliense eléri (Application scope) Egyazon webalkalmazásban lévő összes servlet egyetlen kliense éri el
Request ●
Az adott kérést kiszolgáló komponens éri el
76
Java Server Pages ●
●
●
Lehetővé teszi a prezentációs logika elválasztását magától a prezentációtól –
A prezentáció HTML és/vagy XML/XSLT
–
A prezentációs logikát Java osztályok vagy custom tag-ek valósítják meg a prezentáción belül
Az eredmény egy fokkal jobban karbantartható, mint ha egy servlet-ből out.println(“”)-eznénk Minden .jsp oldalból a deployment során valójában egy out.println()-eket tartalmazó servlet generálódik
77
Java Server Pages ●
Egy szöveges file, ami egy dinamikus tartalmat ír le arról, hogy mit is generálunk vissza a böngésző felé Hello World!
<jsp:useBean id="clock" class=“calendar.JspCalendar” /> Today is - Day of month: <%= clock.getDayOfMonth() %>
- Year: <%= clock.getYear() %>
78
Servlet vs JSP
Servlet • •
HTML Java-ba ágyazva Nehezen karbantartható a statikus tartalom
JSP
• •
•
Java kód HTML-be ágyazva Könnyen karbantartható statikus (HTML) tartalom Futás időben servletként fut, viselkedik
79
Servlet, vagy JSP? ●
A gyakorlatban a kettőt együtt használják ●
●
●
MVC (Model, View, Controller) architektúra A Controller általában egy Servlet A JSP egy lehetséges technológia a View megvalósítására
80
JSTL ●
Szabványos tag library
●
Alapfunkcionalitást tartalmaz gyakori JSP elemekre
●
–
Iteráció és feltételes végrehajtás
–
XML kezelés
–
Direkt adatbázis elérés
–
Lokalizáció
Java kód nélküli deklaratív prezentációs logika létrehozását teszi lehetővé
81
JSTL példa ${customer.lastName} | | no address specified |
82
●
●
Komponens alapú framework-ök A fő ígéret: –
Kérés-válasz és oldalakban gondolkodó alkalmazások helyett valódi objektumorientált alkalmazások fejlesztése
–
Magasabb fokú újrahasznosítás, jobb programozók:)
–
Gyorsabb fejlesztési ciklus, ugyanakkor kevésbé skálázódó alkalmazások
Több megközelítés létezik: –
Echo2, RIFE, Tapestry, Wicket
83
Web programming in Java
84
Web Application & Components ●
Web Application is a deployable package – – – – –
●
Web components (Servlets and JSP's) Static resource files such as images Helper classes Libraries Deployment descriptor (web.xml file)
Web Application can be represented as – –
A hierarchy of directories and files (unpacked form) or *.WAR file reflecting the same hierarchy (packed form)
85
Web Application Development and Deployment Steps 1.Write (and compile) the Web component code (Servlet or JSP) and helper classes referenced by the web component code 2.Create any static resources (for example, images or HTML pages) 3.Create deployment descriptor (web.xml) 4.Build the Web application (*.war file or deploymentready directory) 5.Deploy the web application into a Web container ●
Web clients are now ready to access them via URL 86
1. Write and compile the Web component code ● ●
●
●
Create development tree structure Write either servlet code or JSP pages along with related helper code Create build.xml for Ant-based build (and other application development life-cycle management) process IDE (i.e. NetBeans) handles all these chores
87
Development Tree Structure ●
Keep Web application source separate from compiled files –
●
facilitate iterative development
Root directory (example from hello2 sample code from J2EE 1.4 tutorial) –
build.xml: Ant build file
–
src: Java source of servlets and JavaBeans components
–
web: JSP pages and HTML pages, images
88
Example: hello2 Tree Structure (before “ant build” command) ●
Hello2 –
src/servlets
–
GreetingServlet.java ● ResponseServlet.java web
–
WEB-INF – web.xml ● duke.waving.gif build.xml
●
●
89
2. Create any static resources ●
●
HTML pages –
Custom pages
–
Login pages
–
Error pages
Image files that are used by HTML pages or JSP pages –
Example: duke.waving.gif
90
3. Create deployment descriptor (web.xml) ●
Deployment descriptor contains deployment time runtime instructions to the Web container –
●
URL that the client uses to access the web component
Every web application has to have it
91
4. Build the Web application ●
Either *.WAR file or unpacked form of *.WAR file
●
Build process is made of –
create build directory (if it is not present) and its subdirectories
–
compile Java code into build/WEB-INF/classes directory ●
Java classes reside under ./WEB-INF/classes directory
–
copy web.xml file into build/WEB-INF directory
–
copy image files into build directory
92
Example: hello2 Tree Structure (after “asant build” command) ●
Hello1 –
src
–
web
–
build.xml
–
build ●
●
WEB-INF – classes ● GreetingServlet.class ● ResponseServlet.class – web.xml duke.waving.gif 93
5. Deploy Web application ●
Deploy the application over deployment platform such as Tomcat
94
6. Perform Client Access to Web Application ●
From a browser, go to URL of the Web application
95
http://localhost:8080/hello1/greeting
96
Running Web Application
97
Web Application ●
Web application can be deployed in two different forms – –
●
a *.war file or an unpacked directory laid out in the same format as a *.war file (build directory)
Use *.war file when you have to deploy on a remote machine
98
What is *.WAR file? ●
● ●
Ready to deploy'able package over web container Similar to *.jar file Contains things to be deployed – – – –
●
Web components (servlets or JSP's) Server-side utility classes Static Web presentation content (HTML, image, etc) Client-side classes (applets and utility classes)
Reflects contents in build directory 99
Document Root & Context ●
●
Document Root of the Web application –
Top-level directory of WAR
–
Contains JSP pages, client-side classes and archives, and static Web resources are stored
–
Also contains WEB-INF directory
A context is a name that gets mapped to the document root of a Web application –
/hello1 is context for hello1 example
–
Distinguishes a Web application in a single Web container
–
Has to be specified as part of client URL
100
Directory Structure of *.WAR file
101
Directory Structure of *.WAR file
102
How to Create *.WAR file? ●
3 different ways –
Use IDE (NetBeans)
–
Use ant tool after putting proper build instruction in build.xml file “asant create-war” (under J2EE 1.4 tutorial) Use “jar cvf .war .” command under build directory ●
–
103
Example: Creating hello2.war via “asant create-war” command C:\j2eetutorial14\examples\web\hello2>asant create-war Buildfile: build.xml ... create-war: [echo] Creating the WAR.... [delete] Deleting: C:\j2eetutorial14\examples\web\hello2\assemble\war\hello2.war [delete] Deleting directory C:\j2eetutorial14\examples\web\hello2\assemble\war\WEB-INF [copy] Copying 1 file to C:\j2eetutorial14\examples\web\hello2\assemble\war\WEBINF [copy] Copying 2 files to C:\j2eetutorial14\examples\web\hello2\assemble\war\WEBINF\classes [war] Building war: C:\j2eetutorial14\examples\web\hello2\assemble\war\hello2.war [copy] Copying 1 file to C:\j2eetutorial14\examples\web\hello2 104
Example: Creating hello2.war via jar command C:\j2eetutorial14\examples\web\hello2\build>jar cvf hello2.war . added manifest adding: duke.waving.gif(in = 1305) (out= 1295)(deflated 0%) adding: servlets/(in = 0) (out= 0)(stored 0%) adding: servlets/GreetingServlet.class(in = 1680) (out= 887)(deflated 47%) adding: servlets/ResponseServlet.class(in = 1090) (out= 572)(deflated 47%) C:\j2eetutorial14\examples\web\hello2\build>jar xvf hello2.war created: META-INF/ extracted: META-INF/MANIFEST.MF extracted: duke.waving.gif created: servlets/ extracted: servlets/GreetingServlet.class extracted: servlets/ResponseServlet.class
105
WEB-INF Directory ● ●
Subdirectory of Document root Contains –
web.xml : Web application deployment descriptor
–
JSP tag library descriptor files
–
classes : A directory that contains server-side classes: servlets, utility classes, and JavaBeans components
–
lib : A directory that contains JAR archives of libraries (tag libraries and any utility libraries called by serverside classes)
106
HTTP request URL & Web component URL (alias) & Context ●
●
Request URL: User specified access point of a web resource –
http://[host]:[port]/[request path]?[query string]
–
[request path] is made of context and web component's URL
–
http://localhost:8080/hello1/greeting?username=Monica
Context: Name of the root document of a web application – Identifies a particular application on that server –
/hello1 is context
107
Configuring Web Application ●
Configuration information is specified in web.xml (Web Applications Deployment Descriptor)
108
Web Applications Deployment Descriptor (web.xml) ● ● ● ● ● ● ●
Prolog Alias Paths Context and Initialization Parameters Event Listeners Filter Mappings Error Mappings Reference to Environment Entries, Resource environment entries, or Resources
109
Web Applications Deployment Descriptor (web.xml) ● ●
Case sensitive Order sensitive (in the following order) –
icon, display-name, description, distributable
–
context-param, filter, filter-mapping
–
listener, servet, servlet-mapping, session-config
–
mime-mapping, welcome-file-list
–
error-page, taglib, resource-env-ref, resource-ref
–
security-constraint, login-config, security-role
–
env-entry, ejb-ref, ejb-local-ref 110
Prolog (of web.xml) ●
Every XML document needs a prolog
111
Alias Paths (of web.xml) ●
●
When a request is received by Servlet container, it must determine which Web component in a which web application should handle the request. It does so by mapping the URL path contained in the request to a Web component A URL path contains the context root and alias path –
●
http://:8080/context_root/alias_path
Alias Path can be in the form of either –
/alias-string (for servlet) or
–
/*.jsp (for JSP) 112
Alias Paths (of web.xml) <servlet> <servlet-name>greeting greeting <description>no description <servlet-class>GreetingServlet <servlet> <servlet-name>response response <description>no description <servlet-class>ResponseServlet <servlet-mapping> <servlet-name>greeting /greeting <servlet-mapping> <servlet-name>response /response 113
Context and Initialization Parameters (of web.xml)
● ●
Represents application context Can be shared among Web components in a WAR file <web-app> ... <param-name> javax.servlet.jsp.jstl.fmt.localizationContext <param-value>messages.BookstoreMessages ...
114
Event Listeners (of web.xml) ●
Receives servlet life-cycle events <listener> <listener-class>listeners.ContextListener
115
Filter Mappings (of web.xml) ●
Specify which filters are applied to a request, and in what order OrderFilter filters.OrderFilter OrderFilter /receipt
116
Error Mappings (of web.xml) ●
Maps status code retURLed in an HTTP response to a Java programming language exception retURLed by any Web component and a Web resource
<error-page> <exception-type>exception.OrderException /errorpage.html
117
References (of web.xml) ●
●
Need when web components make references to environment entries, resource environment entries, or resources such as databases Example: declare a reference to the data source jdbc/BookDB javax.sql.DataSource Container
118
Example web.xml of hello2 <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> hello2 <servlet> GreetingServlet <servlet-name>GreetingServlet <servlet-class>servlets.GreetingServlet <servlet> ResponseServlet <servlet-name>ResponseServlet <servlet-class>servlets.ResponseServlet <servlet-mapping> <servlet-name>GreetingServlet /greeting <servlet-mapping> <servlet-name>ResponseServlet /response 119
Servlet Request and Response Model Servlet Container Request
Browser HTTP
Request
Servlet
Response
Web Server
Response
120
What does Servlet Do? ●
● ●
●
Receives client request (mostly in the form of HTTP request) Extract some information from the request Do content generation or business logic process (possibly by accessing database, invoking EJBs, etc) Create and send response to client (mostly in the form of HTTP response) or forward the request to another servlet or JSP page 121
Requests and Responses ●
What is a request? –
●
Information that is sent from client to a server ● Who made the request ● What user-entered data is sent ● Which HTTP headers are sent
What is a response? –
Information that is sent to client from a server ● Text(html, plain) or binary(image) data ● HTTP headers, cookies, etc 122
HTTP ●
HTTP request contains – header – a method ● ● ● ●
–
Get: Input form data is passed as part of URL Post: Input form data is passed within message body Put Header
request data
123
HTTP GET and POST ●
The most common client requests –
●
HTTP GET & HTTP POST
GET requests: – –
User entered information is appended to the URL in a query string Can only send limited amount of data ●
●
.../servlet/ViewCourse?FirstName=Sang&LastName=Shin
POST requests: – –
User entered information is sent as data (not appended to URL) Can send any amount of data
124
First Servlet import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("First Servlet"); out.println("Hello Code Camp!"); } } 125
Servlet Interfaces & Classes Servlet
GenericServlet
HttpSession
HttpServlet
ServletRequest
ServletResponse
HttpServletRequest
HttpServletResponse 126
Servlet Life-Cycle Is Servlet Loaded?
Http request
Load
Invoke
No
Http response
Yes
Run Servlet Servlet Container
Client
Server 127
Servlet Life Cycle Methods service( )
init( )
destroy( ) Ready
Init parameters
doGet( )
doPost( )
Request parameters
128
Servlet Life Cycle Methods ●
Invoked by container –
●
Container controls life cycle of a servlet
Defined in –
javax.servlet.GenericServlet class or init() ● destroy() ● service() - this is an abstract method javax.servlet.http.HttpServlet class ● doGet(), doPost(), doXxx() ● service() - implementation ●
–
129
Servlet Life Cycle Methods ●
init() – –
Invoked once when the servlet is first instantiated Perform any set-up in this method ●
●
Setting up a database connection
destroy() – –
Invoked before servlet instance is removed Perform any clean-up ●
Closing a previously created database connection
130
service() & doGet()/doPost() ●
service() methods take generic requests and responses: –
●
service(ServletRequest request, ServletResponse response)
doGet() or doPost() take HTTP requests and responses: – –
doGet(HttpServletRequest request, HttpServletResponse response) doPost(HttpServletRequest request, HttpServletResponse response) 131
Example: Sophisticated doGet() // Get the identifier of the book to display (Get HTTP parameter) String bookId = request.getParameter("bookId"); if (bookId != null) { // and the information about the book (Perform business logic) try { BookDetails bd = bookDB.getBookDetails(bookId); Currency c = (Currency)session.getAttribute("currency"); if (c == null) { c = new Currency(); c.setLocale(request.getLocale()); session.setAttribute("currency", c); } c.setAmount(bd.getPrice()); // Print out the information obtained out.println("..."); } catch (BookNotFoundException ex) { response.resetBuffer(); throw new ServletException(ex); }
}
} out.println("