Listing 12.17: XMLServerConsole.java package com.psol.xcommerce;/** * handles GET request * @param request HTTP request * @param response hold the response * @exception SerlvetException
Trang 1Listing 12.17: XMLServerConsole.java package com.psol.xcommerce;
/**
* handles GET request
* @param request HTTP request
* @param response hold the response
* @exception SerlvetException error handling the request
* @exception IOException error writing the reply
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{ doProcess(request,response);
}
/**
* handles GET request
* @param request HTTP request
* @param response hold the response
* @exception SerlvetException error handling the request
continues
Trang 2* @exception IOException error writing the reply
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{ doProcess(request,response);
}
/**
* GET and POST requests are forwarded here
* @param request HTTP request
* @param response hold the response
* @exception SerlvetException error handling the request
* @exception IOException error writing the reply
*/
protected void doProcess(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{ String sqlDriver = getInitParameter(“sql.driver”), sqlURL = getInitParameter(“sql.url”), sqlUser = getInitParameter(“sql.user”), sqlPassword = getInitParameter(“sql.password”); try
{ Class.forName(sqlDriver);
Connection connection = DriverManager.getConnection(sqlURL,
sqlUser, sqlPassword);
try { String action = request.getParameter(“action”); if(null != action)
{ if(action.equalsIgnoreCase(“create”)) doUpdates(request,connection,createStatements); Listing 12.17: continued
Trang 3else if(action.equalsIgnoreCase(“drop”)) doUpdates(request,connection,dropStatements);
else if(action.equalsIgnoreCase(“delete”)) doDelete(request,connection);
else if(action.equalsIgnoreCase(“insert”)) doInsert(request,connection);
} doPage(request,response,connection);
} finally { connection.close();
} } catch(Exception e) {
throw new ServletException(e);
} }
“drop table products”,
“drop table orders”, };
private static final String[] createStatements = {
“create table products (id integer not null constraint idconstraint mary key,” +
pri-“name varchar(50),manufacturer varchar(50),” +
“img varchar(30),warranty varchar(20),” +
“description varchar(150),price real)”,
“create table orders (name varchar(50),” +
“street varchar(100),region varchar(50),” +
“postal_code varchar(15),locality varchar(50),” +
continues
Trang 4“country varchar(25),email varchar(50),” +
“productid integer,productname varchar(50),” +
“productprice real,productquantity integer)”
};
/**
* execute a number of updates on the database
* (typically to create schema)
* @param request HTTP request
* @param connection database connection
* @param statements statements to execute
* @throw SQLException one statement throw an exception
*/
protected void doUpdates(HttpServletRequest request,
Connection connection, String[] statements) throws SQLException
{ Statement stmt = connection.createStatement();
SQLException e = null;
try { for(int i = 0;i < statements.length;i++) try
{ stmt.executeUpdate(statements[i]); } catch(SQLException x)
{ e = e != null ? e : x; } if(null != e)
{ throw e;
} } finally { stmt.close();
} } Listing 12.17: continued
Trang 5* delete one product from the database
* @param request HTTP request
* @param connection database connection
* @return the form to display (the result screen if you like)
*/
protected void doDelete(HttpServletRequest request,
Connection connection) throws SQLException
{ PreparedStatement stmt = connection.prepareStatement(
“delete from products where id = ?”);
try { String id = request.getParameter(“id”);
stmt.setInt(1,Integer.parseInt(id));
stmt.executeUpdate();
} finally { stmt.close();
} }
/**
* create a new product in the database
* @param request HTTP request
* @param connection database connection
* @return the form to display (the result screen if you like)
*/
protected void doInsert(HttpServletRequest request,
Connection connection) throws SQLException, Exception
{ String id = request.getParameter(“id”), name = request.getParameter(“name”),
continues
Trang 6manufacturer = request.getParameter(“manufacturer”), image = request.getParameter(“image”),
warranty = request.getParameter(“warranty”), description = request.getParameter(“description”), price = request.getParameter(“price”);
PreparedStatement stmt = connection.prepareStatement(
“insert into products (id,name,manufacturer,img,” +
“warranty,description,price) values(?,?,?,?,?,?,?)”); try
{ stmt.setString(1,id);
} }
/**
* check whether the schema has been created
* @return true if the schema is complete, false otherwise
*/
protected boolean isSchemaCreated(Connection connection) throws SQLException
{ // ask the name of all the tables in the database // check if one of them is “products”
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getTables(null,null,null,new String[] { “TABLE” }); Listing 12.17: continued
Trang 7int found = 0;
while(rs.next()) {
String tableName = rs.getString(“TABLE_NAME”);
if(tableName.equalsIgnoreCase(“products”)
|| tableName.equalsIgnoreCase(“orders”)) found++;
} rs.close();
return 2 == found;
}
/**
* display the page, etc.
* @param request HTTP request
* @param connection database connection
*/
protected void doPage(HttpServletRequest request,
HttpServletResponse response, Connection connection) throws SQLException, IOException
{ Writer writer = response.getWriter();
writer.write(“<HTML><HEAD><TITLE>XML Server Console” +
“</TITLE></HEAD><BODY>”);
Statement stmt = connection.createStatement();
try {
if(isSchemaCreated(connection)) {
Trang 8writer.write(“<TD><INPUT TYPE=\”TEXT\””);
writer.write(“ NAME=\”price\”></TD></TR>”);
writer.write(“</TABLE><INPUT TYPE=\”SUBMIT\””); writer.write(“ VALUE=\”Create\”>”);
writer.write(“<INPUT TYPE=\”HIDDEN\””);
writer.write(“ NAME=\”action\” VALUE=\”insert\”>”); writer.write(“</FORM><P>”);
ResultSet rs = stmt.executeQuery(“select id, name from products”); writer.write(“<TABLE>”);
while(rs.next()) {
Trang 9rs = stmt.executeQuery(“select name, “ +
“productname from orders”);
writer.write(“<TABLE>”);
while(rs.next()) {
} writer.write(“<P><FORM ACTION=\””);
continues
Trang 10{ stmt.close();
} writer.write(“</BODY></HTML>”);
writer.flush();
} }Viewer and Editor
XMLi is a smaller merchant It doesn’t have a Web site or a database.XMLi creates its list of products manually with the editor shown inListings 12.18, 12.19, and 12.20 Listing 12.18 is the Java servlet, Listing12.19 is the JavaScript file, and Listing 12.20 is the XSL style sheet You edit a list of products through a URL like http://localhost /editor?merchant=xmli
Listing 12.18: Editor.java package com.psol.xcommerce;
* Editor is a web-tool to create product lists
* for smaller merchants.
Trang 11* initializes the servlet, read the style sheet
* @exception could not read the style sheet
*/
public void init() throws ServletException {
String fname = getInitParameter(“editor.xsl”);
styleSheet = XMLUtil.parse(fname);
}
/**
* process GET requests
* @param request request received from the client
* @param response response to the client
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{ String merchant = request.getParameter(“merchant”), fname = getInitParameter(merchant + “.xml”);
if(null == merchant || null == fname) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} Document document = XMLUtil.parse(fname);
XMLUtil.transform(document,
styleSheet, response.getWriter(), response.getCharacterEncoding());
}
/**
* handle POST method, HttpServlet forward POST request from service()
continues
Trang 12* to this method
* @param request the request received from the client
* @param response interface to the client
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{ String merchant = request.getParameter(“merchant”), fname = getInitParameter(merchant + “.xml”); if(null == merchant || null == fname)
{ response.sendError(HttpServletResponse.SC_NOT_FOUND); return;
} String pwdRequest = request.getParameter(“pwd”), pwdCheck = getInitParameter(merchant + “.pwd”), xml = request.getParameter(“xmldata”);
if(null != pwdCheck && !pwdCheck.equals(pwdRequest)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN); return;
} Writer writer = new FileWriter(fname);
Trang 13Listing 12.19: Editor.js // editor.js, common code for Editor
var products = new Array();
function addProduct(form) {
// collects data from the form var id = form.id.value, name = form.name.value, price = form.price.value, description = form.description.value;
doAddProduct(form,id,name,price,description);
}
function doAddProduct(form,id,name,price,description) {
var productList = form.productlist, product = new Product(id,name,price,description);
// arrays are zero-based so products.length points // to one past the latest product
// JavaScript automatically allocates memory var pos = products.length;
var productList = form.productlist, pos = productList.selectedIndex;
if(pos != -1)
continues
Trang 14{ var product = productList.options[pos].value;
productList.options[pos] = null;
products[product] = null;
} }
function exportProduct(form) {
var xmlCode = “”, merchant = form.merchant.value, attribute = “merchant=’” + merchant + “‘“;
priceList = null;
form.output.value = “”;
}
function element(name,attributes,content) {
var result = “<” + name;
if(attributes != “”) result += “ “ + attributes;
result += “>”;
result += content;
result += “</” + name + “>\r”;
Listing 12.19: continued
Trang 15return result;
}
function escapeXML(string) {
var result = “”, i,
else if(c == ‘&’) result += “&”;
else result += c;
} return result;
} // declares product object
function Product(id,name,price,description) {
var attrs = “id=’” + this.id + “‘“, result = element(“name”,””,escapeXML(this.name));
result += element(“price”,””,escapeXML(this.price));
continues
Trang 16result += element(“description”,””,
escapeXML(this.description));
return element(“product”,attrs,result);
} Listing 12.20: editor.xsl
<HTML><HEAD><TITLE>Product List Editor</TITLE>
<SCRIPT LANGUAGE=”JavaScript” SRC=”editor.js”>
<xsl:text> </xsl:text></SCRIPT>
<SCRIPT LANGUAGE=”JavaScript”><xsl:comment>
function load(form) {
Trang 17Password: <INPUT TYPE=”PASSWORD” NAME=”pwd”/>
<INPUT TYPE=”SUBMIT” VALUE=”Save”
ONCLICK=”exportProduct(controls)”/>
<INPUT TYPE=”HIDDEN” NAME=”xmldata”/>
<INPUT TYPE=”HIDDEN” NAME=”merchant”>
<?xml version=’1.0’?><products merchant=’xmli’/>
Listing 12.21 and the accompanying style sheet in Listing 12.22 display theorders for XMLi
Listing 12.21: Viewer.java package com.psol.xcommerce;
import java.io.*;
import org.w3c.dom.*;
continues
Trang 18import javax.servlet.*;
import javax.servlet.http.*;
/**
* Viewer is a web-tool to view orders
* for smaller merchants.
* initializes the servlet, read the style sheet
* @exception could not read the style sheet
*/
public void init() throws ServletException {
String fname = getInitParameter(“viewer.xsl”);
styleSheet = XMLUtil.parse(fname);
}
/**
* process GET requests
* @param request request received from the client
* @param response response to the client
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) Listing 12.21: continued
Trang 19throws IOException, ServletException {
String merchant = request.getParameter(“merchant”), path = getInitParameter(merchant + “.orders”), fname = request.getParameter(“fname”);
if(null == merchant || null == path) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} if(null == fname) {
File file = new File(path);
String[] files = file.list();
Writer writer = response.getWriter();
writer.flush();
} else { File file = new File(path,fname);
Document document = XMLUtil.parse(file.getPath());
XMLUtil.transform(document,
continues
Trang 20styleSheet, response.getWriter(), response.getCharacterEncoding()); }
} } Listing 12.22: viewing.xsl
<TR><TD>Street:</TD>
<TD><xsl:value-of select=”order/buyer/@street”/></TD></TR>
<TR><TD>Region:</TD>
<TD><xsl:value-of select=”order/buyer/@region”/></TD></TR>
<TR><TD>ZIP or postal code:</TD>
<TD><xsl:value-of select=”order/buyer/@postal-code”/></TD></TR>
<TR><TD>Locality:</TD>
<TD><xsl:value-of select=”order/buyer/@locality”/></TD></TR>
<TR><TD>Country:</TD>
Listing 12.21: continued
Trang 21<TD><xsl:value-of select=”order/buyer/@country”/></TD></TR>
<TR><TD>E-mail:</TD>
<TD><xsl:value-of select=”order/buyer/@email”/></TD></TR>
<TD ALIGN=”RIGHT”><xsl:value-of select=”@quantity”/></TD>
I hope you enjoyed reading this book as much as I enjoyed writing it
Trang 23Appendix A
Crash Course on Java
If you are a JavaScript, Perl, or C++ programmer and you are not familiarwith Java, this appendix is for you Java is a natural companion to XML.This appendix teaches you just enough Java to be able use it with XML
In this appendix, you learn
• how Java compares to JavaScript and other programming languages
• why Java is important for XML
• how to install a Java runtime environment and run Java applications
• enough Java to read and write simple programsYou don’t have to become a super-trooper in Java programming, but somefamiliarity with “the other Web language” is required for serious fun withXML If anything, there are more XML tools available in Java than in anyother language
✔ If you want to quickly learn how to run the Java package introduced in Chapter 3, turn to the section “Downloading Java Tools,” on page 459, and the section “Understanding the Classpath,”on page 480.
Java in Perspective
There is lot of discussion about the relative importance of Java and XML
In my experience, they are complementary Admittedly, I am somewhatbiased in favor of Java I formed my company, Pineapplesoft, with a focus
on Java development At the time, I bet on the importance of cross-platformapplications
I believed (and still do) that a low level object-oriented programming guage for the Internet is required C++ is low-level but is not portableenough (you can’t run the same program unmodified on differentmachines)
lan-XML is not a programming language, just as HTML is not a programming
Trang 24language XML is a language to encode information That is useful but youalso need programming to manipulate the information in XML documents.One of the major misconceptions is that Java equals applets Applets mighthave been popular in the early days of Java but they never had a fightingchance against Macromedia Flash or Dynamic HTML For simple anima-tion, JavaScript is simpler than Java For complex animation, Flash ismore efficient.
The value of Java lies elsewhere In combination with XML, Java is ularly relevant for
partic-• heavy-duty server-side applications
• components for scripting languages
Furthermore, a typical organization might have all of these platforms ning at once, and your application might have to run on both UNIX andWindows servers
run-Finally, for servers, portability equates with scalability: When new ware is introduced to boost the performance, existing software must stillrun on it As an added bonus, software can be developed on cheap machinesand deployed on high-end servers
hard-Components of the Server-Side Applications
Increasingly, we rely on scripting languages—such as JavaScript, Perl,Python, or ColdFusion—to combine components such as an XSL Processor
or database access
Scripting languages are high-level programming languages They are ally interpreted and typeless This makes them able to create applicationsquickly These languages are at their best when they are gluing componentstogether
usu-XML fits well with this style of programming The numerous companionstandards (DOM, SAX, XSL, CSS, X-Schema, RDF, and so on) are beingmade available as components
Scripting languages are not the best tool for writing components For one
Trang 25thing, it is difficult to integrate scripting languages with one another.Furthermore, because scripting languages are high level, they are less effi-cient.
Java is well adapted to write these components because it is a compiled,low-level programming language Additionally, most scripting languagescan interface with Java components Java portability means that the com-ponents are available on a large number of platforms In Java, components
are called JavaBeans.
As has already been noted, there are more XML components (parsers, XSLprocessors, conversion, and so on) written in Java than in any other lan-guage
Downloading Java Tools
This section lists the various pieces you need to run the examples in thisbook I have chosen software that is available free of charge when possible
If you find yourself doing lots of Java development, however, you will want to buy an integrated development environment such as Café(www.symantec.com), Visual Age (www.software.ibm.com), or JBuilder(www.inprise.com)
Java Environment
The trick behind Java portability is the Java Virtual Machine or JVM Java programs are compiled to a portable binary format, called the class files To
execute the binaries, you need a JVM
The JVM is available on most platforms You can download a JVM for yourplatform from java.sun.com It comes in one of two versions:
• Java Runtime Environment (JRE) is a naked JVM It can run existingJava applications but lacks the tools to develop new ones
• Java Development Kit (JDK) offers everything in the JRE as well asdevelopment tools such as the compiler
If you plan to run the examples in this book, you need a JDK to compilethem If you are interested in running only existing packages (such asLotusXSL), a JRE is enough
At the time of this writing, there are three major generations of JVMs:
• JDK 1.0 is the original version Seldom used anymore, it was slow andlimited