XML and JSP interaction technology

Source: Internet
Author: User
Tags abstract add empty hash opening and closing tags string tag name version
js|xml| interaction

Both XML and JSP are technologies that have emerged in the last two years and have become a hot topic for many programmers. XML (Extensible Markup Language) is a framework for defining document markup languages, which are used primarily to store and send data information so that data can be exchanged more easily between various web-based applications. JSP is a server-side program Dynamic design language, can be used to design a variety of server-side programs such as Business-to-business, Business-to-consumer and other systems, because of its object-oriented, compiled and implemented, robust and other characteristics, has been more and more applications.
A very useful technique is how to combine XML with JSP, fortunately, we don't have to write down the support layer, because many manufacturers such as Sun, IBM and so on have released their own XML-enabled APIs, in which Sun offers a API-JAXP that supports the use of XML in Java ( JAVATM API for XML processing Optional Package), which provides the basic ability to read and write and manipulate XML documents, so that we can easily integrate XML into Java applications.
The current JAXP version is 1.1 and supports SAX 2.0, DOM 2, and XSL technology in addition to basic XML support. The JAXP provided by Sun Company can be downloaded from Sun's homepage http://java.sun.com/xml.
One, JAXP installation
1, before installation, please confirm that you are using JDK 1.1.8 version of the Java environment.
2, in the Http://java.sun.com/xml download JAXP1.1 zip version, extracted to the hard disk, the assumption that the extract directory for #jaxp11, after decompression found that there are three jar files Jaxp.jar Crimson.jar Xalan.jar, this is the heart of JAXP.
3, modify the system Classpath variable, in the Windows platform to add such a line:
#JAXP11 \jaxp.jar; #JAXP11 \crimson.jar; #JAXP11 \xalan.jar
Add the following line under the Unix/linux system:
#JAXP11/jaxp.jar: #JAXP11/crimson.jar: #JAXP11/xalan.jar Alan.jar
If you're using JAVA2, there's a simpler way to copy the three files directly into the JDK's Lib extension directory, such as #java_home/jre/lib/ext (#JAVA_HOME代表JDK目录), So you don't have to change the classpath.
4, OK, the installation is complete, the next step is to write the program and then run.
Second, simple examples of XML
XML (extensible Markup Language) is an HTML-like language, unlike HTML, where XML is used primarily to describe structured data, and in XML format we can easily exchange data between various applications. And these are traditional technologies that take a lot of effort to do.
Let's take a look at a simple example of an XML document, this example saves some of the personal files, save it as a personal.xml file, because our JSP file will also call the data in the middle of it.

< personal files >
< name > Liu Yufeng
< sex > Male
< age >24
Coolknight@263.net
< personal homepage >http://www.21jsp.com
< introduction > Welcome to visit my homepage!
  
Is it very similar to HTML files, such as the elements in HTML "Hello", and so on, because XML and HTML are all subsets of standard SGML, so there are similarities. But there are a lot of different things to note, such as XML files that have to be tagged and case sensitive, which are allowed by default in HTML.
The first line is the required XML declaration, we can see that the declaration is between, the middle can define some of the attributes, version= "1.0" means that the document will use the XML1.0 specification, encoding= "gb2312" means to use the Chinese character set, So we can use Chinese for the data below.
Then there is the < personal file > tag, which is the root element in the XML file, is also indispensable, and must have a corresponding closing tag, between the opening and closing tags we can define our own data description.
Nested in < personal files > tags such as "< name > Liu Yufeng" is a specific data description, the same root element must be a pair of tags, in the middle of the tag can be a specific number of tags. This notation is somewhat similar to the records in the database, the field name is "name", "gender", and so on, the above XML file is equivalent to a single record of the table "personal files." Of course, there are multiple layers of nesting in an XML file, but this is not covered in this article.
Of course, this is just a very simple example of XML, XML is more relevant content, if you want to learn more about XML, suggest or read the relevant books.

Third, JSP and XML interaction
As already mentioned, JSP through the Sun Company's API-JAXP can be implemented and XML interaction, then the implementation of the main two methods, one is to use the DOM2 API, the other is the use of the SAX2 API.
Here we discuss the sax in Jaxp (simple API for XML parsing) technology, DOM2 technology can look at sun company-related documentation.
1 About SAX Models
The SAX model is a way to process an XML file, which is event-driven and is similar to the event-driven mechanism in AWT, which identifies the contents of an XML document through event-driven. The main aspects of Sax in the API are the following packages:
Oorg.xml.sax
Oorg.xml.sax.helpers
Oorg.xml.sax.ext
Java and XML interactions can be well implemented in the foreground Java program or in a JSP program by invoking the APIs in these packages.
2) About Handlerbase interface
We know that in AWT it is common to implement event processing by implementing interfaces such as ActionListener, and similarly in sax, Sun also provides a similar interface handlerbase to handle XML parsing functions, You can work with XML files well by associating handlerbase with XML files.
In the implementation interface we mainly overload three Handlerbase methods Startelement (String tag, attributelist attrs), characters (char[] ch, int start, int length) , EndElement (String name).
Startelement () Fires when reading the start tag of a row of XML data, and subclasses must override this method so that they can do their own processing before processing the XML node (for example, when starting reading or writing to nodes in an XML file).
public void Startelement (String name, attributelist attributes)
Throws Saxexception
{
No op
}
The parameter name represents the XML node name, attributes represents the default or special attribute, and this method throws an offending org.xml.sax.SAXException.
Characters () method is mainly used to deal with and between the specific data, in the processing of node data trigger, we can override this method for data manipulation processing, you can add code to read the node data value or write node data values.
public void characters (char ch[], int start, int length)
Throws Saxexception
{
No op
}
Parameter ch[] represents an array of characters, start represents the beginning of a character array, length represents the number of elements in ch[in the array of characters to be taken, and the same method throws an offending org.xml.sax.SAXException.
The EndElement () method triggers when the end of a node element is handled, that is, when the tag is encountered, we can override this method to finish the data, such as writing the node data to the file.
public void EndElement (String name)
Throws Saxexception
{
No op
}
The parameter name represents the XML node name, and this method throws an illegal org.xml.sax.SAXException
As we can see from the above, the order of the three methods in the XML event processing sequence is:
Startelement () àcharacters () àendelement () (String name)
Maybe it's hard to understand. Below we will write a class MyHandler class to implement the Handlerbase interface, and overwrite these three main methods to implement our XML file read operation.
3) About hash tables
Because the program uses a hash table, here is a brief introduction to the basic syntax of the hash table so that you can better understand the following program.
Hash table hashtable is derived from the dictionary, which has a series of keywords and numeric values, a keyword corresponding to a number, recognition is mainly through the object's hash code hashcode recognition.
The methods used in our program are as follows:
Put (Object key,object value) Add a pair of keywords/values to the hash table
Get (Object key) gets its value based on the keyword
Keys () gets all the keywords and returns a collection enumeration
In addition, a hash table has many other useful methods, such as length size (), whether it is empty empty (), whether to repeat ContainsKey (), and so on, which is not covered here.

4) Implement Handlerbase interface
Here we write a MyHandler class that implements the Handlerbase interface and overwrites the three main methods of the interface startelement (String tag, attributelist attrs), characters ( char[] ch, int start, int length), endelement (String name) so that the XML file can be manipulated.
In order to save the data so that the external program can call the data in this class, we use a hash table structure to save all the node names after parsing the XML file and the data values of the nodes, Startelement () method is mainly used to read the node names in the XML file, characters () The method is mainly used to read the node data according to the node name, and the EndElement () method is mainly to store the node name and node data in the hash table after an XML node has been processed.
In the external program we only need to call the GetTable () method to return a hash table object to read all node and node data values.
The code is not much, and I added a lot of comments below, it should be very good to understand.
Myhandler.java file
file://files are placed in the package com.jsp21.www
Package com.jsp21.www;
file://import of related Java APIs
Import java.io.*;
Import org.w3c.dom.*;
Import org.xml.sax.*;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import java.util.Hashtable;
Import java.util.Enumeration;
The MyHandler class implements the Handlerbase interface;
public class MyHandler extends Handlerbase {
Private String myelement = null; The tag name in the File://XML file;
Private String myvalue = null; File://XML the corresponding value in the file;
Private Hashtable mytable = new Hashtable (); FILE://is used to save all the data in the XML file;
file://gets a hash table hashtable with XML data stored;
Public Hashtable gettable () {
return mytable;
}
file://overrides the Startelement method in the Handlerbase interface to execute this method when reading the start tag of a row of XML data;
Tag represents the markup in XML, such as the name age in the preceding XML file;
public void startelement (String tag, attributelist attrs)
Throws Saxexception {
MyElement = tag;
}
The file://covers the characters method in the Handlerbase interface, which is mainly used to obtain and the specific data between them;
When the corresponding MyElement mark finds the value, that is, after the Startelement method is executed, the characters method is triggered to get the concrete numerical value.
file://such as myelement= "name" time, myvalue will be equal to "Liu Yufeng";
public void characters (char[] ch, int start, int length)
Throws Saxexception {
myvalue = new String (CH, start, length);
}
file://covers the EndElement method in the Handlerbase interface, which is mainly used for the processing of one row of XML data after reading.
This endelement method is triggered when a row of tags in an XML file is read;
file://if there is a corresponding closing tag, the preceding token myelement and value myvalue
file://into the mytable hash table;
public void EndElement (String name) throws Saxexception {
if (myelement.equals (name)) {
Mytable.put (MyElement, myvalue);
}
}
}
Well, compile this class and place the Myhandler.class file in a path that classpath can find, such as the Web-inf\classes\com\jsp21\www directory of the application in Tomcat.

5 JSP program calls XML
Here, we write a relatively simple JSP program to call the previous MyHandler class, and through this class to read the contents of the Personal.xml file, and finally displayed in the JSP page.
First we create a saxparserfactory instance of SAXPF, and then through this instance, we create a SAXParser instance Saxpser (which can be used to parse the XML file content) and, of course, create instances of the MyHandler class, Finally, the XML file is associated with the MyHandler class instance through the Saxpser.parse () method (this will perform several event-handling methods in MyHandler).
(Note: SAXParserFactory is an abstract class that defines a factory API that allows Java applications to be configured or to obtain a SAX parser (SAX parser). SAXParser is also an abstract class that enables you to parse the contents of an XML file. )
By this time, all XML content is stored in the hash table in the MyHandler class instance, and finally the hash table object is obtained by the GetTable () method, and the keys in the hash tables are saved in the collection enumeration. Use a loop to read data from the Harlem table and display it on the JSP page. The purpose of our collection is to make this JSP program as versatile as possible, passing an XML file name to read all the content, and of course you can read a particular node value without using a collection instead of using a method such as "name" ("Hshtable.get").
The following is the JSP file code, please save it as a jspxml.jsp file
This is a xml+jsp example of reading the contents of an XML file

   
The code is well written, put this file in the Web application directory, and then run the program through the browser, such as http://192.168.0.98:7070/welcome_html/jspxml.jsp?file=e:\\ Personal.xml, note that you must use parameters? file= path \\personal.xml (the path is based on the directory you save on your hard disk, Java says: "\ \" is a "\" on the Windows system), and the effect is as follows:


As you can see, all the data in the XML file is read through this JSP file, because the JSP program is file-independent, you can also change the XML file name in File=e:\\personal.xml to other XML files to see the last run effect.
To illustrate the point is that I actually adopted the JAXP1.01 version of the API, there may be my system reasons, the Discovery program in version 1.1 can be compiled, but the runtime will be the following error (even if the JAXP1.1 package with the example of the Main.java also):
Java.lang.NoClassDefFoundError:org.apache.crimson.jaxp.SAXParserFactoryImpl
So finally the 1.01 version of JAXP is used to run the program, and the 1.01 version of JAXP can also be downloaded at the address above.



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.