Overview:
XML and JSP are the hottest things in these days. This article describes how to combine these two technologies to build dynamic websites. You can also take a look at examples of Dom, XPath, XSL, and other Java-XML technologies. Code .
Let's assume that you already know about JavaServer Pages (JSP) and Extensible Markup Language (XML ). However, you may still be confused about how to use them comprehensively.
JSP applications are easy to use. You can use it to design webpages and make them look the same as HTML. The only difference is that JSP is dynamically executed. For example, they can process form forms and read/write databases.
It is difficult to describe the XML application. It seems that all products support it, and everyone seems to be using it for various purposes.
In this article, you can see how to design a system using XML in a fairly advanced way. Many sites collect massive amounts of data and display them in a very standard or unstandard manner. I will design a system that uses XML files for storage on the Web server and JSP to display data.
XML vs Relational Database
"Wait! "You may ask," Are you using an XML file to store data? Why not use the database? "
This is a good question. My answer is that it is too wasteful to use databases for many purposes .. To use a database, you must install and support a separate server processing process (a separate server process), which usually requires the Administrator to install and support it. You must learn SQL, use SQL to write queries, convert data, and return data. If you use an XML file to store data, you can reduce the load on the server. Also, you have found a simple way to edit data. You only need to use a text editor instead of complex database tools. XML files can be easily backed up, shared with friends, or downloaded to your client. Similarly, you can easily upload new data to your site through FTP.
XML also has a more abstract advantage, that is, as a hierarchical format is better than relational. It can be used directly to design the data structure to meet your needs. You do not need to use an entity-link editor or standardize your chart schema. If one element contains another element, you can directly represent it in the format without using Table Association.
Note: In many applications, relying on file systems is insufficient. If there are many updates, the file system will be damaged due to simultaneous writing. Databases usually support transaction processing and can cope with the requests that occur without being damaged. Complex query statistics must be updated repeatedly and in a timely manner, and the database performance is excellent at this time. Of course, relational databases also have many advantages, including rich query languages, graphic tabulation tools, scalability, and access control.
(Note: You can use simple File Locking to provide a transaction processing server. You can also execute an XML index-and-search tool in Java, but this is another article. Article .)
In the following example, as for most small and medium-sized sites based on published information, most of the data you may involve is read rather than write. Although the data may be large, but it is not updated frequently, and you do not need to perform complicated queries. Even if you need to do so, you will also use an independent query tool, the advantages of mature RDBMS disappear, while those of Object-oriented Data models can be reflected.
Finally, it is entirely possible to provide a queryer shell for your database to perform SQL queries and convert them into an XML Stream.
So you can choose either of the two methods. XML is becoming a very robust and easy-programming tool. It is used as a front-end tool for storage and query of a mature database. (Oracle XSQL servlet is a good example of this technology .)
Application: an online album
Everyone enjoys photography! They like to show photos of their loved ones, friends, and vacations, while Web is a good place for them. -- Even if you are a relative of a thousand miles away, you can see it. I will focus on defining a separate picture object. (This application's Source code In resources ). This object describes the fields required for a photo: title, date, an optional title, and a point to the image source.
An image requires some of its own fields: location, width, and height of the source file (GIF/JPEG) pixels (to assist in the creation of the mark. Here we can see a very simple advantage, that is, when you use a file system to replace the database, you can store graphical files in the same directory as the data files.
Finally, let's extend the image record with an element that defines a set of thumbnails (thumbnail) for content tables or other places. Here I used the same image content as previously defined.
The XML Representation of an image can be as follows:
<Picture>
<Title> Alex on the beach </title>
<Date> </date>
<Caption> trying in vain to get a tan </caption>
<Image>
<SRC> alex-beach.jpg </src>
<Width> 340 </width>
<Height> 200 </Image>
<Thumbnails>
<Image>
<SRC> alex-beach-sm.jpg </src>
<Width> 72 </width>
<Height> 72 </Image>
<Image>
<SRC> alex-beach-med.jpg </src>
<Width> 150 </width>
<Height> 99 </Image>
</Thumbnails>
</Picture>
Note: By using XML, you can store all the information of a single image in a separate file instead of distributing it into 3-4 tables. We call this. pix File
-- So your file system will be like this:
Summer99/ alex-beach.pix
Summer99/ alex-beach.jpg
Summer99/ alex-beach-sm.jpg
Summer99/ alex-beach-med.jpg
Summer99/ alex-snorkeling.pix
Etc.
Technology
As the saying goes, there is only one way to peel off a cat's skin. Similarly, there are more than one way to put XML data into JSP. Some of the methods are listed here (in fact, many other tools can do the same well .)
DOM: You can use a class (classes) to call the DOM interface to analyze and check XML files.
Xmlentrylist: You can use my code to load XML to Java. util. List of name-value pairs.
XPath: You can use an XPATH processor (such as resin) to locate elements in an XML file by path name.
XSL: You can use an XSL processor to convert XML into HTML.
Cocoon: You can use the open-source cocoon framework.
Run your own bean: you can write a Wrapper class and use some other technology to load data into the word-defined JavaBean.
Note that these technologies will be executed equally well with an XML Stream you obtained from another source, such as a client or an application server.
Assumerver pages
JSP specifications have many substitutes. Different JSP products have different performance and different versions have different performance. I chose Tomcat for the following reasons:
It supports most of the latest JSP/servlet specifications
It is recognized by Sun and Apache
You can run it independently without configuring another Web server.
It is open source
You can choose any JSP Engine you like, but to configure it yourself, it must support at least the JSP 1.0 specification. There are many differences between 0.91 and 1.0. The jswdk (Java Server Web Development Kit) may have just been well suited to requirements.
JSP Structure
When creating a JSP website (webapp), I like to put public functions, imports, constants, and variable declarations into a separate file init. jsp. Then load the file with <% @ include file = "init. jsp" %>. <% @ Include %> is like C Language # Include, include: the include> flag is used to compile the file independently, and then embed a call to it in the file.
Search for files
When JSP is started, the first thing after Initialization is to find the XML file you want. How does it know which one of the many files you are looking? It comes from a parameter. The user will add the parameter picture. jsp in the URL that calls JSP? File = summer99/alex-beach.pix (or passing file parameters through HTML forms ).
However, when JSP accepts this parameter, you are still only half done, because you also need to know where the root directory of the file system is. For example, in a UNIX system, the actual file may be in the following path:
/Home/Alex/public_html/pictures/summer99/alex-beach.pix.
The JSP file does not have the current path concept during execution. Therefore, you must provide an absolute path for the java. Io package.
Servlet API can provide a method to convert a URL path from the path relative to the current JSP or servlet to an absolute file system path. The method is:
Servletcontext. getrealpath (string ).
Each JSP has a servletcontext object called application. So the code can be:
String picturefile =
Application. getrealpath ("/" + request. getparameter ("file "));
Or
String picturefile =
Getservletcontext (). getrealpath ("/" + request. getparameter ("file "));
It can also work in servlet. (You must add/because this method needs to pass the result of request. getpathinfo .)
Here is an Important Note: Whenever you access local resources, you must carefully check the legitimacy of the input data. Hackers or careless users may send forged or wrong data to destroy your site. For example, consider the following results:
If file =.../etc/passwd is input. In this way, the user reads the password file of your server!
Dom (Document Object Model)
Dom represents the Document Object Model. It is a standard API for browsing XML documents, developed by World Wide Web Consortium (W3C. The interface is in the org. W3C. Dom package. For more information, see W3C site.
There are many available Dom analyzer tools. I chose IBM xml4j. But you can use any other dom analyzer. This is because Dom is a set of interfaces, rather than a class-all Dom analyzers (parser) must return objects that process these interfaces in the same way.
Unfortunately, although standard, Dom has two major defects:
1. Although API is also object-oriented, it is still quite bulky.
Dom parser does not have a standard API, so when each analyzer returns an org. w3C. DOM object, Document Object-the method in which the analyzer initializes and loads the file itself, which is usually specific to different analyzer.
The simple image file described above can be represented as follows in the DOM in a tree structure through some objects:
Document Node
--> Element node "picture"
--> Text node "\ n" (whitespace)
--> Element node "title"
--> Text node "Alex on the beach"
--> Element node "date"
-->... Etc.
To get "Alex on the beach", you need to call some methods and explore the DOM tree. In addition, the analyzer may choose to scatter some data of the "whitespace" text nodes, you have to use loops and concatenation (you can call normalize () to correct this problem .) Analyzer may also contain separated XML entities (such as &), CDATA nodes, or other entity nodes (such as <B> big <B>), which are converted into at least three nodes. There is no way to simply represent "Get me the text value of the title element." In short, traveling in the Dom is a little cumbersome. (See replacing Dom With XPath in this article .)
2 from a higher point of view, the problem with Dom is that XML objects cannot be directly obtained like Java objects. They need to be obtained one by one through DOM APIs.
You can refer to some of the summaries I have made for the Java-XML data binding technology, where I also used this method to directly use Java to access XML data.
I wrote a small tool class called domutils, which contains static methods to execute common Dom tasks. For example, to obtain the text content of the title sub-element of the root (image) element, you can write the following code:
Document Doc = domutils. xml4jparse (picturefile );
Element noderoot = Doc. getdocumentelement ();
Node nodetitle = domutils. getchild (noderoot, "title ");
String title = (nodetitle = NULL )? Null: domutils. gettextvalue (nodetitle );