js|xml| Create | dynamic | Site XML and JSP are the most popular topics today. This article guides you through the use of both techniques to create dynamic Web sites. Use the XML file to store the data and use the JSP file to display it. You can also learn about other java-xml techniques such as DOM, XPath, XSL, and more.
Author Alex Chaffee
Let me first assume that readers, like most other Java programmers, have some knowledge of JSP (JavaServer Pages) and XML (extensible Markup Language), but don't know how to use them. In this article, you will learn how to design a system in XML. Many sites have a large number of data in different formats, and their performance is more or less not followed by a certain standard. And I recommend this method to design a Web site, that is, to save the data with an XML file, the JSP file to display the data.
Presumably everyone already knows the limitations of HTML. As the site grows, a way is needed to share and exchange data. Whether it's content sales, order Processing, or report generation, you need to define the data. XML works just fine, and other applications can only read and translate information, and XML can give meaning to the data. You might find it strange why you use XML to store data instead of databases. The answer is that in many applications, the database is a bit too "fierce". In order to use the database, you have to install and support a separate server processing, install DBMS, build DBA, and learn the SQL language, learn how to write query statements and return the results. But if you use an XML file, you don't have to spend it to prepare an additional database server, and the advantage is that it's easy to edit the processing data, like a text editor, rather than a complex database management tool. XML files are also easy to back up, share and download, and upload new data to the site via FTP.
Another slightly abstract advantage of XML is that it uses a hierarchy rather than a relational structure to define the data, which can be used directly to the design application's data structure, or to use entity relational Designer to standardize the schema. If you have a member that contains another member, you can express it directly through the hierarchy without using a join table. In this sense, XML is beneficial to the expression of information and structured organization, which can define data accurately, so that data search is more effective.
For many applications, the file system does not have enough capacity to meet the needs. When a large amount of data needs to be updated, its weaknesses are exposed. Concurrent write-operation conflicts are big issues. The database has good transaction processing capabilities, rich indexes and complex queries, and can provide a wrapper for the database so that queries are created and converted into XML streams. The XML becomes a powerful and programming-friendly front-end component of the database (Oracles XSQL servlet is an example of implementation).
Defining data in XML: an example of an online album
Everyone likes photos. The Internet is a tool that can show itself, friends, filling things and various activities. This example defines a simple photo object (source code can be obtained from the Resources section). Shows the attributes required to define a photo object are: Title, date, brief description, and location of the image.
Define the attributes required for an image:
Location of image files (GIF or JPEG)
Height of image (pixel)
Width of image (in pixels)
The simple advantage of storing information in a file system as a database is that the image file and the data description file can be saved in the same location.
Finally, an element is used to define the small photo image (thumbnail images) set to augment the definition of the photo record so that it can be used everywhere.
Examples of XML to define photos are as follows:
<picture>
<title>alex on the beach</title>
<date>1999-08-08</date>
<caption>trying in vain to get a tan</caption>
<image>
<src>alex-beach.jpg</src>
<width>340</width>
</image>
<thumbnails>
<image>
<src>alex-beach-sm.jpg</src>
<width>72</width>
</image>
<image>
<src>alex-beach-med.jpg</src>
<width>150</width>
</image>
</thumbnails>
</picture>
With XML, you can put all the information about a picture in a simple file, not in a scattered table. This file is called the pix file. This way the file system looks like the following.
Summer99/alex-beach.pix
Summer99/alex-beach.jpg
Summer99/alex-beach-sm.jpg
Summer99/alex-beach-med.jpg
Summer99/alex-snorkeling.pix
etc.
There are several ways to combine XML data with JSP pages. Several options are listed below:
DOM: Using classes to implement DOM interfaces to parse and view XML files
Xmlentrylist: Loading XML into Java.util.List's Name-value pair
XPath: Using the XPath processor (like resin) to locate elements in the XML by path name
XSL: Converting XML to HTML with an XPath processor
Cocoon: Cocoon Framework with open code
Roll your own bean: can write a wrapper class to load data into a custom JavaBean
These methods can be used equally well to accept XML streams when the client or application server side is accepted.
Java Server Pages
JSP has many implementation versions, and different JSP versions implement different and incompatible specifications. The author chooses Tomcat here based on several reasons:
It supports the latest JSP and Servlet specs
Sun and Apache recognize it
You can run it on your own without having to configure a single Web server
It's open source
(For more information on Tomcat, see resources.)
You can use your favorite JSP engine casually, but you need to configure it yourself. Be sure to verify that the selected engine supports JSP1.0 specifications. The versions from 0.91 to 1.0 are different from one place to the other. Just JSWDK (Java Server Web Development Kit) works.
JSP Construction
When constructing a JSP-driven Web site, it is recommended that common functions, import modules, constants, and variable definitions be placed in a separate file named Init.jsp. It is then added to each JSP file using the <% @include file= "init.jsp"%>. The <% @include%> instructions are similar to the #include definition characters in C, which is compiled with the contents of the containing file (for example, init.jsp) as the content of the containing file (for example, picture.jsp). Note that, as a comparison, the <jsp:include> flag instructs the compiler to compile it as a stand-alone JSP file and embed a call to it in the compiled JSP.
Find Files
When you start the JSP, the first thing to do after the initialization is to find the XML file you need. How do you know what documents are needed? The answer is to use a CGI program to pass the required parameters. A user can pass a file parameter by URL Picture.jsp?file=summer99/alex-beach.pix or by using an HTML form object.
When the JSP receives the parameters, you also need to know where the filesystem root directory is located. Under the UNIX system, the file location is specified in a/home/alex/public_html/pictures/summer99/alex-beach.pix manner. The JSP does not have the concept of a relative path when executing, so it must provide an absolute path within the java.io package.
The servlet apt function provides a way to convert a URL path to an absolute path, depending on the version of the JSP or Servlet being used. Servletcontext.getrealpath (String) is the trick to implement. Each JSP version has a ServletContext object (called a application). So the code can look like this:
String PictureFile =
Application.getrealpath ("/" + request.getparameter ("file"));
Or
String PictureFile =
Getservletcontext (). Getrealpath ("/" + request.getparameter ("file"));
They can also work in the servlet. Note that "/" must be added because the result of the Request.getpathinfo () will be passed to this method.
It is also important that when accessing local resources, special care must be taken of the data transmitted, hackers or careless users may send fake data to black your site. For example, with file=. /.. /.. /.. /ETC/PASSWD, users can look at the password of the server.
Document Object Model
The DOM represents the document Object Model, which is a set of standard APIs for browsing XML documents. Developed by the World Wide Web Consortium (The World Consortium). Its interface is within the package org.w3c.dom, and its documentation is located in the Web site (resources).
There are many implementations of DOM parsers. Because the DOM is a collection of interfaces rather than the definition of a class, each parser must return an object that faithfully implements those interfaces. I chose the xml4j that IBM realized.
Although the interface set is standard, the DOM has two major flaws:
1. API function, although it is an object-oriented implementation, but still quite cumbersome
2. No standard APIs are designed for DOM parsers, although each parser returns org.w3c.dom.Document objects, but the initialization of the parser and the loading of the file are always unique to the various parsers.
The photo file described above, if expressed in DOM, can be described by several objects in the tree structure:
Document Node
--> Element Node "Picture"
--> Text Node "" (whitespace)
--> Element Node "title"
--> Text Node "Alex on the Beach"
--> Element Node "Date"
--> ... etc.
In order to get the value "Alex on the Beach", several methods must be called to traverse the DOM tree. Further, the parser can choose to access any number of blank nodes. Parsers can also include distinguishing XML entities (such as &), CDATA nodes, or other element nodes (for example, the:<b>big<b> bear can be converted to at least 3 nodes.) One of these is element B, which contains a text node with a text value of big. There is no way in Dom to simply say: "Get me the text value of the title element." It's OK. In short, traversing the DOM tree is not pleasant.
From another high point of view, the DOM problem is that accessing an XML object cannot be as straightforward as accessing a Java object. Access to them must be decomposed through the DOM API.
Refer to my conclusions in the Java-xml data binding technology discussion where you can access the XML data directly by accessing the Java object.
I wrote a little tool class Domutils, which contains static methods to implement common DOM tasks. For example, to obtain the contents of the child node (title) of the root node (picture), you can write the following code:
The code above picture-dom.jsp is not appealing. When you want to place a lot of Java code inside the JSP, there is a neat way: You can use JSP JavaBeans to store a lot of Java code. The advantage is that the JSP script tags (<% and%>) can be saved in the JSP page to facilitate program flow and reduce the operation of variables. For prototyping purposes, putting all the Java code in a JSP may start to feel easy and enjoyable. You can also go back to the necessary code and put it into JavaBeans after you have a good idea. This is a bit expensive, but will be rewarded in the future if your application needs to be modular. You can use the same beans on different pages without having to do annoying copy-and-paste to support code reuse.
In the example above, extracting the value of a string from an XML file can be used as a JSP JavaBean. Defines the Picture,image,thumbnails class to represent the main elements in the XML. These beans will have constructors or setter methods that call the DOM node or filename to extract the desired value from it. The source code of Picturebeans package can be found from resources or picture-beans.jsp.
Please note when reading the source code:
Interfaces are defined outside of the implementation class, so the change implementation can be freely chosen in the future. You can store data in the list, in the DOM, and even in the database.
The beans is defined within a custom package Picturebeans. All JSP beans must be placed in a package; most JSP engines cannot find classes in the default package.
The Set method is also provided in addition to the Get method. Now, you can only read and not change the properties of the picture. You can change these properties in the future to allow users to edit pictures.
Since the required values are stored in beans rather than in local variables, you must use <%=picture.getcaption ()%> instead of <%=caption%>. Of course, you can also define local variables such as String caption = Picture.getcaption ();. This makes the code easier to understand.
Using thumbnails to zoom in
In the output of the first JSP, a full-size image file is displayed. You can modify the code slightly to show a list of slightly smaller images. This will use the list of images stored in the XML data file.
First, you define a parameter zoom, which determines which thumbnails image to display. Click the mouse on the small image to see the full size of the original image. Click the Zoom in and Zoom out button to select the next or previous thumbnails image.
Thumbnails object returns java.util.List Image object, it is not easy to find the correct thumbnails object, just Say (Image) picture.getthumbnails (). Get (i) is not enough.
When you do Zoom in and Zoom out links, you must generate recursive calls to the same page with different parameters. This allows you to use the Request.getrequesturi () method. Simply passing the path to the servlet requires no additional parameters, so you can attach the parameters you need.
<%
if (Zoom < (thumbnails.size ()-1)) {
Out.print ("<a href=" +
Request.getrequesturi () +
"? file=" + request.getparameter ("file") +
"&zoom=" + (zoom+1) +
">");
Out.print ("Zoom in</a>");
}
%>
This is the HTML screenshot of the Working JSP page.
Here is an example of how JSP pages work.
Using JSP bean tags
The <jsp:useBean> tag is defined in the JSP specification to automatically instantiate and use JavaBeans in JSP pages. Usebean tags can often be replaced by embedded Java code. I have replaced it here. Based on this, many people are asking questions about when Usebean and setproperty tags need to be used. There are several things about these tags:
Tag syntax does not interfere with HTML designers
Usebean has a scope parameter that automatically determines whether beans should be stored in a local or session variable or as a application property.
If the variable is long term valid (session or application), Usebean initializes it if necessary, but only if the variable already exists.
Tags potentially have a number of advantages for future JSP version specifications that can be flexibly changed. (for example, a hypothetical JSP engine can store variables in the database or share them through the server process)
For this application, the equivalent Usebean syntax is as follows:
To overcome some of the difficulties of using the DOM API, a Xmlentrylist class was made. It implements the Java set interface Java.util.List and contains the Java.util.Map Get,put method, and provides a direct method set to traverse the simple XML tree structure. You can use the standard extraction methods of the collection API to do things like queries, iterations, and child views. Each entity in the Entity list has keys and values, just like a map object. A key is the name of a child node, a value, or a string or a xmlentrylists.
Xmlentrylist is not a complete substitute for DOM. There are several DOM features that it cannot implement. However, it is a handy wrapper for doing basic getting, setting,list-oriented functions to handle XML data structures. For example, to get the value of the caption attribute of the picture node, you can write this:
The value of the caption attribute is parsed and stored in a string.
Caching cache
Regardless of the advantages of an XML file, parsing it takes a lot of time. In order to improve the performance of xml-based applications, some caching techniques must be used. The cache must store the XML object in memory based on the XML file name. If the XML file has been updated since the last load, you must reload it. I did a simple tool for implementing this data structure Cachedfs.java. You can use an inner class to use Cachedfs as a callback function to implement XML parsing, which transforms a file into an object. The cache can store objects in memory.
Here is the code that generates the cache. This object has the scope of the application and can be reused. This code is put into the init.jsp.
<jsp:usebean id= "Cache" class= "Com.purpletech.io.CachedFS" scope= "Application" >
<% Cache.setroot (Application.getrealpath ("/"));
Cache.setloader (New Cachedfs.loader () {
Load in a single picture file
Public Object process (String path, InputStream in) throws IOException
{
try {
Document doc = Domutils.xml4jparse
(New BufferedReader (New InputStreamReader (in));
Element noderoot = Doc.getdocumentelement ();
Noderoot.normalize ();
Picture picture = new Dompicture (noderoot);
return to picture;
}
catch (XmlException e) {
E.printstacktrace ();
throw new IOException (E.getmessage ());
}
}
});
%>
</jsp:useBean>
Xpath
XPath is a simple syntactic unit for locating XML tree nodes. It is easier to use than DOM. When you want to enter the next node from a node, you do not have to invoke the making method. You can embed all the paths into a string, such as/picture/thumbnails/image[2]. In resin, the XPath object is included and can be invoked directly in the application.
Node verse = Xpath.find ("Chapter/verse", node);
Xsl
This article discusses how to embed Java code in a JSP to extract data from XML nodes. There is also a popular model to do the job. Is the XSL (extensible Stylesheet Language). It is completely different from the JSP model that has been discussed. In JSP, the main document model is HTML, contains Java code, and in the XSL Chinese file model is XSL, containing HTML. There is much to discuss about the relationship between XSL and java/jsp. This is limited to space, it is not deep. In the future, you will discuss the problems with XSL and JSP in Javaworld.
The conclusion and the way of looking ahead
After reading this article, readers should have a good understanding of the structure and strengths of the Jsp-xml application and the flaws.
The most tedious thing in developing jsp-xml applications is to construct JavaBeans for each element of the XML schema. XML Data Binding Group is developing technologies that can automatically generate Java classes from a given pattern. I also developed a prototype for Java-xml data binding that exposes the source code. IBM Alphaworks recently also published XML Master or (Xmas), which is another java-xml data-binding system.
Another possibility is to expand the functionality of the file system and construct some of the more powerful features, such as querying or handling things. Naturally, I'm also considering developing source-code-exposed projects to implement this functionality. Who wants to write an XML search engine?
The source code in the article can be found below:
Http://www.javaworld.com/jw-03-2000/jspxml/jspxml-webapp.zip
For future updates to that source code:
http://www.purpletech.com/jspxml/
Xml:
http://www.xml.org/
http://www.xml.com/
Http://www.jguru.com/faq/XML
SML, a controversial simplification of XML syntax:
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.