Overview of XML and JSP

Source: Internet
Author: User
Tags execution extend file system functions sql object model string variable
Js|xml

XML and JSP are the hottest things in these days. This article describes how to unite these two
Technology to build dynamic Web sites. You can also look at dom,xpath,xsl at the same time,
and other java-xml techniques for example code.
Let's assume you already know JavaServer Pages (JSP) and extensible
Markup Language (XML). But maybe you still have some of the ways to use them synthetically.
Confused.
The application of JSP is easy, you can use it to design the Web page so that it looks and HTML a
Sample. The only difference is that the JSP is dynamically executed. For example, they can work with form form
and read and write databases.
The application of XML is more difficult to explain. It seems that all products are supported by it and everyone
It seems to be using it for a variety of different purposes.
In this article, you can see how to use XML in a rather advanced way to design a
A system. Many sites have massive data collection and are in a very standard or non-standard way
To show them. I'm going to design a system that uses an XML file to do it on a Web server
and use a JSP to display the data.
XML vs Relational database
"Wait a minute!" "You might ask," Do you store data in an XML file? Why not use a database? "
This question is very well asked. My answer is that for many purposes, using a database is too
It's a waste. To use a database, you must install and support a separate server
Processing process (a separate server process), which often requires installation and support for it
's Administrator. You have to learn SQL, write queries with SQL, and then transform the data,
and return. And if you store data in an XML file, you can reduce the extra server's negative
Load Also, you've found a simple way to edit the data. You just use a text-editing
Editors without having to use complex database tools. XML files are easy to back up, and friends altogether
Enjoy, or download to your client. Similarly, you can easily upload new
Data to your site.
XML also has a more abstract advantage, that is, a hierarchical format is better than a relational type.
It can be used in a very direct way to design data structure to meet your needs. You don't need
To use an entity-relational editor, you do not need to make your chart (schema) standard
Of. If you have an element that contains another element, you can directly
It is represented in the format without the use of the table's Association.
Note that in many applications, it is not sufficient to rely on file systems. If you update a lot,
The file system is corrupted because of simultaneous writes. The database typically supports transaction processing,
Can cope with requests that occur without damage. For complex query statistics to be repeated
, timely updates, at this time the database performance is excellent. Of course, relational databases Also
There are many advantages, including rich query language, charting tools, scalability, access
Control and so on.
(Note: You can use a simple file lock to provide a transaction processing server, you also
You can execute an XML index-and-search tool in Java, but this is already
The subject of another article. )
In the following cases, as in most small and medium sized, post based information stations
Point, you may be involved in most data access is read, not written, although the data
It may be very large, but it is relatively not always updated and you do not need to do very
Complex query, even if you need to do, will also use a separate query tool, then into
The benefits of a cooked RDBMS are gone, and the advantages of an object-oriented data model can be
to embodiment.
Finally, provide your database with a query shell for SQL queries and turn them
It is also entirely possible to enter the XML stream.
So you can choose one of these two ways. XML is becoming a very robust, easy to
Programming tools to store and query as a front-end tool for a mature database.
(Oracle's xSQL servlet is a good example of this technique.) )
Application: an online album
Everyone likes to take pictures! They like to show their own, loved ones, friends, vacations
Photos while the Web is a good place for them to show. --even if relatives thousands of miles away
can be seen. I will focus on defining a separate picture object. (This application of
Source code can be obtained in resources. This object describes what is required to represent a picture
Fields to: Title,date, an optional caption, and a reference to the source of the picture
To.
An image that requires some of its own fields: source file (gif/jpeg) positioning, wide
degree and height pixels (to assist in building marking.) Here you can see a very simple
Advantage, that is, when you use the file system instead of the database, you can save the graphics file
Placed in the same directory as the data file.
Finally, let's extend the picture record with an element that defines a set of abbreviations
Diagram (thumbnail) for content tables or other places. Here I used the same as before
The content of the picture defined.
The XML representation of a picture can be this:
<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>
Note that by using XML, you put all the information of a separate picture into a single
File instead of spreading it into 3-4 tables.
We'll 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.
Technical Articles
As the saying goes, there is more than one way to peel a cat's skin. Also, put the XML data into the JSP
There are more than one way. Some of these methods are listed here (in fact, many other workers
can also do equally well. )
DOM: You can use the class (classes) to invoke the DOM Interface (interface) on XML
File for analysis and inspection.
Xmlentrylist: You can use my code to load XML into Name-value
Pairs in the java.util.List.
XPath: You can use an XPath processor (such as resin) to pass the path name in the XML
Locate the element in the file.
xsl: You can use some kind of XSL processor to convert XML into HTML.
Cocoon: You can use the Open source Cocoon framework
Run your own bean: You can write a shell class (wrapper class), using a
Other techniques to load data into the javabean of a word definition.
Please note that these techniques will be executed in the same way as an XML stream that you have obtained from another source
Excellent, such as a client or an application server.
JavaServer Pages
JSP specifications have many aliases, different JSP product performance is not the same, different versions
There are also differences. I chose Tomcat, which is based on the following reasons:
It supports most of the latest Jsp/servlet specifications
It was recognized by Sun and Apache
You can run it on your own without having to configure a different Web server.
It's open source.
You can choose any JSP engine you like, but to configure it yourself, it must at least branch
Hold JSP 1.0 specification. There are many differences between 0.91 and 1.0. and JSWDK
(The Java Server Web Development Kit) may have just been well suited to requirements.
JSP structure
When creating a JSP site (Webapp), I like to use common functions, imports, constants,
Variable declarations are placed in a separate file init.jsp. and use
<% @include file= "init.jsp"%> loaded into every file.
<% @include%> is like the #include of the C language, include at compile time to make the
Text as a part is joined and compiled together, and relatively, <jsp:include>
The tag is to have the file be compiled independently, and then embed a pair in the file
It's called.
Find Files
When the JSP starts, the first thing to do after initialization is to find the XML file you want. How does it
Do you know which one you're looking for in a lot of documents? It comes with a parameter, the user
Adds a parameter to the URL that invokes the JSP: Picture.jsp?file=summer99/alex-beach.pix
(or pass a file parameter through an HTML form).
However, when the JSP accepts this parameter, you still have only half the work done, because you have to
Know where the root directory of the file system is. For example, in a UNIX system, the actual file might
In such a path:
/home/alex/public_html/pictures/summer99/alex-beach.pix.
The JSP file does not have the current path concept when executing state. So you're going to give the java.io package
An absolute path.
The Servlet API can provide a way to place a URL path, from relative to the current JSP
or the path of the servlet into an absolute file system path. The method is:
Servletcontext.getrealpath (String).
Each JSP has a ServletContext object called application. So generation
The code can be:
String PictureFile =
Application.getrealpath ("/" + request.getparameter ("file"));
Or
String PictureFile =
Getservletcontext (). Getrealpath ("/" + request.getparameter ("file"));
It can also work in a servlet. (You must add/because this method needs to be passed Request.getpathinfo
() results. )
Here's an important tip: whenever you access local resources, be very careful to check the legality of the input data

Hackers or unwary users may send bogus or erroneous data to destroy your station.
Point. For example, think about what will happen to the following expressions:
If you enter a file= ... /.. /.. /.. /etc/passwd. So the user reads back to your
Server's password file!
DOM (Document Object Model)
The DOM represents the Document object model. It is browsing the XML document
A standard API, developed by World Wide Web Consortium (The World Consortium). Interface
In the Org.w3c.dom package, the documentation is shown in the Web site.
There are a number of DOM parser tools available. I chose IBM's xml4j. But you can use
Any other DOM parser. This is because the DOM is a set of interfaces, not classes--all
The DOM parser (parser) must return objects that handle these interfaces as well.
Unfortunately, despite the standard, Dom has two major drawbacks:
The 1 API is also object-oriented, or rather unwieldy.
DOM parser does not have a standard API, so when each parser returns a
A Org.w3c.dom object, a Document object--the parser initialization and the side that the file itself loads
Type, which corresponds to a different parser is usually always specific.
This simple picture file described above can be used in a tree structure in the DOM
Some objects are represented as follows:
Document Node
--> Element Node "Picture"
--> Text Node "\ n" (whitespace)
--> Element Node "title"
--> Text Node "Alex on the Beach"
--> Element Node "Date"
--> ... etc.
In order to get "Alex on the Beach", you have to do some method calls to travel DOM
Tree, and the parser may choose to scatter some number of "whitespace" text nodes
According to, you have to use loops and concatenation etc. (you can call normalize () to
Correct the problem. The parser may also contain separate XML entities (such as &),
CDATA nodes or other entity nodes (such as <b>big<b> will be turned into at least three
Node There's no way to simply represent "Get me the text value of" in the DOM
The title element. "In short, traveling in the DOM is a bit unwieldy. (See this article
Replace the DOM chapter with XPath. )
2 from a higher point of view, the problem with the DOM is that XML objects cannot be as straightforward as Java objects
, they need to be obtained one by one from the DOM API.
You can refer to my summary for the Java-xml Data binding technical discussion,
It also uses this direct Java-like approach to accessing XML data.
I wrote a small tool class called Domutils, which contains a static method to perform a public
Dom task. For example, to get the text of the title child element of the root (picture) element
Allow, 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)
;
The value that gets the image child element is also straightforward:
Node nodeimage = Domutils.getchild (Noderoot, "image");
Node nodesrc = Domutils.getchild (nodeimage, "src");
String src = domutils.gettextvalue (NODESRC);
Wait a minute.
Once you need to use Java variables for each of the related elements, what you have to do is change
Amount embedded in HTML tags:
<table bgcolor= "#FFFFFF" border= "0" cellspacing= "0" cellpadding= "5" >
<tr>
&LT;TD align= "center" valign= "Center" >
<%=src%> "></td>
</tr>
</table>
Model/view separation with a JSP bean
All the picture-dom.jsp code above is very appealing. Although you can add tens of thousands of them in your JSP
Java code, but this doesn't look easy with the JSP JavaBeans method.
JavaBean stores a lot of Java code and calls it in a JSP script.
To make a model, put all the Java code in the JSP to start a project, so
relatively simple. Once you have any new ideas you can go straight back and expand the code, and then rewrite
For some JavaBeans. Although the investment is higher, but in the long run the return is better, because your should
With more modeling. You can reuse the bean in multiple pages without worrying about the clip
To the bad consequences.
In our case, a typical JSP JavaBean is to expand the string from the XML.
You can define the picture, image, and thumbnails class to represent the main XML file
The element in. These beans with the constructor constructors or setter method, which
Take a DOM node or a filename from the unwind value. You can join
Test Picturebeans bag or picture-beans.jsp.
Please note the following when looking at the code:
* I separate the definition of the interface from the execution of the class so that you can freely choose the future
Instead, you can store the value in a list, or in the DOM itself, or even
To be in the database.
* The bean is defined as--picturebeans in a custom package. All JSP beans must
Need to be in a package. Most JSP engines cannot discover classes from the default package.
* In addition to the Get method, I also provided the Set method that currently you are only reading, but in the future,
You have to let the user edit the picture, so you have to plan the language to modify the function of writing the property.
* <%=picture.getcaption ()%> replaces <%=caption%&gt, because the value is stored
In a bean, not in a local variable. However, if you need to, you can place the local
variable is defined as
String caption = Picture.getcaption (); This is also allowed, which can make
Code is easier to read and understand.
 
* Zoom out by thumbnails
You may have noticed the output of my first JSP, picture-dom.html,
The source picture files of all sizes are used. We can modify the code a little bit to make it look
With a thumbnail, I'll store the thumbnail list in an XML data file.
Let's define a parameter, zoom, whose value determines which thumbnail to display. Point
Click the thumbnail to show the full size of the picture; zoom in or Zoom Out button
The next/previous thumbnail in the select list.
* Because the Thumbnail object returns the java.util.List of an image object, you must find
The correct thumbnail is not easy if you use (Image) picture.getthumbnails ().
* To make Zoom in and Zoom out connections, you must create a recursive reference to the same page, but
Use a different parameter. To do this, you use the Request.getrequesturi () method. This
Just provide you with the path to the servlet, no parameters, so you can fill in the parameters you want here.
<%
if (Zoom < (thumbnails.size ()-1)) {
Out.print ("<a href=") +
Request.getrequesturi () +
"? file=" + request.getparameter ("file") +
"&zoom=" + (zoom+1) +
"' >");
Out.print ("Zoom in</a>");
}
%>
Here is a screen copy of HTML.
Http://www.javaworld.com/jw-03-2000/jspxml/picture-dom.html
Using JSP beans
The JSP specification defines the <jsp:useBean> tag for automatic instantiation and use of JavaBeans. Usebean tags can always
Is
Replaced by embedded Java code, and here's what I do. And for that reason.
It is sometimes questioned what is necessary to use Usebean and setproperty tags. This
The advantages of this approach are:
Markup syntax helps HTML designers work independently.
Usebean has a scope parameter that automatically determines whether the bean must be stored as a
A local variable, a session variable, or a application property.
If this variable is persistent (session or application), Usebean can be
Initialize it and cut it when it does exist to get the variable.
In the long run the tags are more portable (portable) or more in future JSP specification versions
Change execution (for example, a hypothetical JSP engine stores a variable in a database, or
Users share data across servers. )
The corresponding Usebean statement in this application is:
<jsp:usebean id= "Picture" scope= "Request" class= "Picturebeans. Dompicture ">
<%
Document doc = Domutils.xml4jparse (picturefile);
Element noderoot = Doc.getdocumentelement ();
Noderoot.normalize ();
Picture.setnode (Noderoot);
%>
</jsp:useBean>
Alternatively, if you define a Setfile (String) method in Dombean:
<jsp:usebean id= "Picture" scope= "Request" class= "Picturebeans. Dompicture ">
<jsp:setproperty name= "Picture" property= "file" value= "<%=picturefile%>"/>
</jsp:useBean>
Using Xmlentrylist
To overcome some of the deficiencies of the DOM APIs, I created a class called Xmlentrylist. This class
Executed the Java collections interface Java.util.List, and Java.util.Map's
Get and put methods, which provide a more intuitive approach to the structure of a simple XML tree
To move back and forth in. You can use the standard abstraction (abstraction) of the collections API to
To get an iteration or a view of a child. There's a key at every entrance to the entrylist.
Key and a value, just like the map; The key is the name of the child nodes.
The value is either a string or the next level (child) xmlentrylists.
Xmlentrylist does not mean that the DOM can be completely replaced. It also fails to perform certain DOM
Function. However, it is a handy shell (wrapper) on your XML data structure
Used to perform basic getting, setting, and list-oriented functions. For example
You can use this notation to get the caption element of the picture node:
String caption = (string) picturelist.get ("caption");
The value of the caption field has long been parsed and stored as a string.
Cache Caching
Although there are many advantages, parsing an XML file always takes time. In order to improve the base
For the performance of XML applications, you need to use some sort of caching technique. This cache must be in memory
To remember which file they come from, save the XML objects in the If the object is loaded after the file
has been modified, the object needs to be reloaded. I've developed one for this data structure
The simple method, called Cachedfs.java. You can supply a CACHEDFS call to return
function, which uses an internal class that actually performs XML parsing to convert a file into a
An object. The cache can then store that object in memory.
Here is the code to create the cache, this object has application scope, so thereafter the
Requests can use the same object cache. I'm going to put this code in the init.jsp so you
You don't have to clip these initialized code into other JSP files. In short, you must
Define the Application-scope object in a public place.
<jsp:usebean id= "Cache" class= "Com.purpletech.io.CachedFS" scope= "Applicatio"
N ">
<% 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 syntax for locating node in XML tree. It's more than DOM
Easy to use, because
When you want to transfer to another node without having to generate a method call every time, you can put the whole
A path is embedded in a string, for example:
/PICTURE/THUMBNAILS/IMAGE[2].
The resin product contains an XPath processor that you can add to your application
In. You can use the Caucho XPath object to load itself without having to purchase resin
System of other products.
Node verse = Xpath.find ("Chapter/verse", node);
Resin also contains a scripting language that is compatible with JavaScript and allows you to
Simple access to XPath and XSL.
Xsl
This article discusses embedding Java in a JSP to expand data from XML node. Finish doing the same
Sample work can also have another common model: Extensible Stylesheet Language (XSL).
There is a fundamental difference between this model and the JSP model. In JSP, the main content is HTML, which contains the
Some Java snippets; In XSL, the primary content is the XSL document, which contains some
HTML fragment. If you want to discuss the relationship between XSL and java/jsp, the space here is already
It's not enough. An article in Javaworld magazine will explore how to use both XSL and
Jsp.
The present conclusion and the future development of the road
After reading this article, I believe you should have a jsp-xml application and its powerful power
A good idea and structure of understanding. But you also need to know some of its limitations.
The most frustrating thing about developing jsp-xml applications is that the elements in each XML schema
element to create JavaBean. The XML Data Binding organization is developing a technology that
Java classes can be generated automatically for each given schema. In the same way, I have developed
A prototype-open source Java-xml data binding technology. In addition, IBM
Alphaworks recently also launched the XML Master, or called Xmas, which is another
A kind of xml-java data binding system.
Another possibility is to extend the functionality of the file system to create some more powerful features,
such as query and transaction processing. Naturally, I also began to expect that this type of functionality could also be used as
Open source engineering to be developed. Well, is there anyone who would like to write an XML search engine



Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.