Currently, Java 2 Platform Enterprise Edition (J2EE) architecture is highly praised in the vendor market and the developer community. As a tool, the Extensible Markup Language (XML) simplifies data exchange and inter-process message exchange, so it gradually becomes attractive to developers and becomes popular. Naturally, the idea of accessing or integrating XML solutions in a J2EE architecture is also attractive. This will be a combination of powerful system architecture and highly flexible data management solutions.
XML applications seem to be endless, but they can be divided into three categories:
* Representation and exchange of simple data (Simple API (SAX) and Document Object Model (DOM) Syntax Parsing for XML, different Document Type Definitions (dtds) and summary (Schemas ))
* Message-oriented computing (XML-RPC (remote process call), SOAP protocol, E-Business XML (ebXML ))
* User Interface-related and contextual representation (Extensible style sheet language (XSL) and extensible style sheet language conversion (XSLT ))
These applications have a natural correspondence in the J2EE architecture: the data representation and exchange functions are part of the persistence services in the EJB component model, message-based communication is handled by the Java Message Service (JMS) API, and the interface representation is just a masterpiece of Java Server Pages (JSP) and Java Servlets.
In this article, we will see how XML is applied in the above aspects in today's J2EE-based applications and how these applications will develop in the future versions of relevant standards.
Basic: data expression and exchange
The content of a prototype XML application (if any) is usually stored in XML format, it is often read into an object model for display, modification, or even writing into an XML document. For example, assume that we are processing multiple types of media (images, videos, text documents, and so on), and use the simple xml dtd below to describe the metadata of these media:
<! -- DTD for a hypothetical Media Management System --> <! -- Media assets are the root of the object hierarchy. assets are also Hierarchical-they can contain other assets. --> <! Element media-asset (name, DESC ?, Type *, media-asset *, urn)> <! -- Metadata about the asset --> <! Element name (# pcdata)> <! Element DESC (# pcdata)> <! Element type (DESC, mime-type?)> <! Element mime-type (# pcdata)> <! Element urn (# pcdata)> |
The following is an XML document based on the media DTD that describes the content related to a course Lecture:
<? XML version = "1.0"?> <! Doctype media-asset public "-// Jim Farley // DTD media assets //" http: // localhost/articles/Sun/dtds/media. DTD ";> <Media-asset> <Name> lecture 14th </Name> <DESC> all content related to lecture 14th </DESC> <! -- A set of child components of the Content Object "Lecture 14" --> <Media-asset> <Name> Lecture slides </Name> <Type> <DESC> MS PowerPoint </DESC> <Mime-type> application/vnd. MS-PowerPoint </mime-type> </Type> <Urn> http://javatraining.org/jaf/E123/lecture-14/slides.ppt <;/urn> </Media-asset> <Media-asset> <Name> video clip of the lecture </Name> <Type> <DESC> RealPlayer streaming video </DESC> <Mime-type> video/vnd. Rn-realvideo </mime-type> </Type> <Urn> http://javatraining.org/jaf/E123/lecture-14/lecture.rv <;/urn> </Media-asset> <! -- Lecture start --> <Urn> http://javatraining.org/jaf/E123/lecture-14/index.jsp <;/urn> </Media-asset> |
From the perspective of web or enterprise-level applications, it is a good news to access data in this way, because it reflects a high degree of mobility and isolates us from the actual resources of metadata. These resources may come from a relational database system, an active media server, or a static XML file on a Web server. If you want to load the data to a Java application, you can choose one from the numerous Java language XML parser, load the XML data into a DOM document, and finally traverse the document, convert all the data to the object model of our application system.
The following is a simple dom-based parsing program that can parse the media DTD. The parser uses Apache xerces:
Package JAF. xml; Import java. util .*; Import java. Io. ioexception; Import org. W3C. Dom .*; Import org. xml. Sax .*;// XML file parser, which uses the media DTD above. Public class mediaparser implements errorhandler { /** Use the Apache xerces parser */ Org. Apache. xerces. parsers. domparser mparser = New org. Apache. xerces. parsers. domparser (); /** Constructor */ Public mediaparser (){ // Tell the parser to verify and parse the document Try { Mparser. setfeature ("http://xml.org/sax/features/validation";, true ); } Catch (saxexception e ){ System. Out. println ("error setting validation on Parser :"); E. printstacktrace (); } // Set the parser's error handling handle Mparser. seterrorhandler (this ); } /** Parse the specified URL and return the found XML file */ Public document. nbsp; parse (string URL) throws saxexception, ioexception { Mparser. parse (URL ); Document. nbsp; mediadoc = mparser. getdocument .); Return mediadoc; } /** Parse the XML document of the specified URL and convert the content into a mediaasset object */ Public Collection loadassets (string URL) throws saxexception, ioexception { Document. nbsp; Doc = parse (URL ); Collection assets = new sorted list (); Nodelist assetnodes = Doc. getelementsbytagname ("media-asset "); For (INT I = 0; I <assetnodes. getlength (); I ++ ){ Node assetnode = assetnodes. item (I ); Mediaasset asset = new mediaasset (assetnode ); Assets. Add (asset ); } Return assets; } /** * Error handling code (omitted for simplicity) */ } |
The constructor of the mediaparser class initializes an xerces Dom parser. The parse () method tells the parser which URL to find the XML source, and then obtains the result document and returns it. The loadassets () method calls the parse () method to load the document from an XML source, and creates a mediaasset object for each "media-asset" Node found in the document.
The following is an example of using the mediaasset class:
Package JAF. xml; Import java. util .*; Public class mediaasset { // Resource metadata Private string mname = ""; Private string mdesc = ""; Private collection mchildren = new jsonlist (); Private vector mtypes = new vector (); Private string murn = ""; Protected mediaasset (Org. W3C. Dom. node assetnode ){ // Omit the following code for the sake of conciseness . . . } } |
The detailed code of the mediaasset class is omitted because of the length, but the application mode is still clear. The mediaasset class traverses the document node. when it encounters different subnodes, it fills in its member data with the content of the subnode. If it discovers a nested sub-resource node, it only needs to create a new mediaasset object, and then fill the data of the sub-resource node into the member data of the new object.
There are countless ways to implement the above processing. We can also use other parser or parser architectures, such as Java API for XML parsing (JAXP ). In addition to the DOM model, the event-driven sax model can also be used to parse XML. Similar programs can also be used to generate XML data-provided that new data objects (mediaasset in this example) can be generated, and the corresponding XML entities can be inserted into the Dom, then output the Dom to a stream (such as a file, a socket, or an HTTP connection ...). There are other high-level standards that can further automate (or simplify) the process of ing XML to Java objects ). For example, you can use XML Summary (schema) to bind a processing engine with XML to convert XML data that meets an XML summary to a Java Data Object semi-automatically. The representative engine is Castor, a product of an open-source project managed by the exolab team. The simple example of using xerces Dom above only demonstrates the underlying model of the processing process.
The above example shows that parsing or generating XML in the Java environment is very convenient, which is not necessarily related to J2EE. Data formatted as XML can be imported or output from any layer of the application, which makes integration with external systems unlimited. But can we integrate the XML data source into the J2EE architecture in a more direct way?
Control Messages
The J2EE architecture includes the access to the JMS (Java Message Service) API to implement message-oriented communication (for J2EE 1.2.1, only the jms api is required. In J2EE 1.3, the JMS is basically finalized, a jms api provider must be provided by a server compatible with the J2EE platform ). This type of Asynchronous interaction (in contrast to the synchronous interaction represented by local or remote method calls) proves to be very useful in some application environments. In some cases, interactions only need to be implemented through indirect requests or answers, that is, in some cases, the reply cannot be received immediately after a message is sent, however, we still want to ensure that the sender can receive a reply when going online again.
One of the practical applications for message systems is the loose integration between enterprises. Similar to the document exchange in the EDI (Electronic document exchange) era, two enterprises exchange messages due to business needs, in this case, you cannot closely integrate the two methods to use remote methods such as RPC, RMI, CORBA, and DCOM for interaction. Message systems like JMS APIs allow both parties to exchange message loads based on JMS APIs, provided that both parties can provide compatible jms api services during the session. The difficulty is whether the two parties can respect the same format or agreement.
This is exactly the time for XML to show its strength. XML is clearly designed to solve such data exchange problems-the panacea is "message-oriented summary table" (message-oriented communication scheme), which is based on a DTD or schema recognized by both parties, exchange message loads in XML format.
The jms api supports several messages. textmessage indicates the text message load. A simple and effective XML message exchange solution is to insert our XML document into textmessage at one end, and then use a self-made XML parsing program (such as the Front mediaparser) at the other end) unbind data and (optional) convert it to a Java object. This allows us to use the public subscription message model supported by the jms api or the point-to-point message model supported by the jms api to send XML messages.
The preceding method has some limitations, because the XML content is basically not transparent for JMS runtime processing. For example, the jms api allows a route based on a specific message header. This is easy to understand, especially when we want XML messages to take different directions based on their content. For example, in our mediaasset example, we want to publish the lecture content, but only want to transmit the specific content to those who have subscribed to the course, or to those who indicate they can accept certain media formats (such as video streams. To make full use of the value of the jms api to achieve the above content-based message routing, We need to parse key information from the XML data and then insert this information when constructing the standard jms api message header. This is feasible, but to implement XML Information, We need to write a lot of code (both parties exchange messages ).
To bridge the gap between XML and JMS APIs, some vendors provide custom JMS extensions to directly support the XML message mechanism. For example, BEA's WebLogic application server based on J2EE provides a subclass of xmlmessage for textmessage, allowing XML messages to be filtered using XPath expressions. However, this is a proprietary extension, which requires that both Parties that exchange messages must be able to process such messages.
To this end, Sun is currently developing a Java API (jaxm) for XML messages ). The goal is to provide an advanced standard service for the synthesis and transmission of ebXML-based messages. A jaxm service provider can map such messages to appropriate physical message systems (such as JMS APIs.
Make XML visible
It is obviously a beneficial attempt to integrate XML with the web system user interface. The vast majority of interface programs, whether based on or not based on the Web, convert data and display it to users in a readable format. Storing data in a "Easy-to-Digest" format such as XML simplifies the above work and greatly improves the manageability of the content. Next we can see this. However, the first thing to write is that the application of XML in the Web interface layer is benefited from the development of JSP technology.
We have always hoped to clearly distinguish the presentation layer and underlying Object Model of Web applications. The JSP framework was born from these efforts (including early JHTML attempts ). The JSP framework allows you to embed Java code into HTML content. This allows you to implement dynamic content without having to modify Java Servlets code frequently. The way to include Java Technology in the page is through JSP tags, which appear in XML style. In JSP, Java programs exist in the form of code snippets, server-side JavaBeans components, and opaque tags (standard or custom) that trigger specific operations on the server. When a user requests a JSP page through a browser, a Java application server parses the JSP page, compiles it into a Java Servlet, and then executes the servlet to generate a response page.
One way to directly integrate the XML data source into the JSP interface is to load the XML data into the JavaBeans component (as we did in the mediaasset example ), then directly reference these JavaBeans components in JSP.
The following is an example of embedding a Java code snippet:
<HTML> <Head> <Title> media resources in lecture 14th </title> </Head> <Body> <! -- Introduce our class --> <% @ Page import = "JAF. xml. *" %> <Center> <! -- Define a resource object for display --> <JSP: usebean class = "JAF. xml. mediaasset" id = "asset"/> <! -- Load resources from a previously defined location --> <% Mediaparser parser = new mediaparser (); Collection assets = parser. loadassets ("http://javaschool.org /JAF/e162/lecture14-assets.xml "); Iterator iter = assets. iterator (); %> <Table border = 0> <Tr> <TH> name </Th> <TH> type </Th> <TH> urn </Th> </tr> <% While (ITER. hasnext ()){ Asset = (mediaasset) ITER. Next (); %> <Tr> <TD> <JSP: getproperty name = "asset" property = "name"/> </TD> <TD> <JSP: getproperty name = "asset" property = "type"/> </TD> <TD> <JSP: getproperty name = "asset" property = "Urn"/> </TD> </Tr> <% } %> </Table> </Body> </Html> |
The bold part is the JSP code snippet and tag, and the rest is the standard HTML text.
There is also a more concise way of writing the above program, that is, using custom JSP page tag. In this way, we can extract the code segment from the JSP page and only use the JavaBeans component and custom JSP tag. For example, in order to remove the code that creates a parser and loads resource data into the collection, we can create a tag of our own, which will be done behind the scenes. The following is an example:
.
.
.
<! -- Introduce our class -->
<% @ Page import = "JAF. xml. *" %>
<Center> <! -- Load our custom tag library -->
<% @ Taglib uri = "http://javaschool.org/taglib"; prefix = "Media" %>
<! -- Load resources from a previously defined location -->
<Media: Load url = "http://javaschool.org/jaf/E162/lecture14-assets.xml ";
Collectionname = "assets" cursorname = "asset"/>
<Table border = 0>
.
.
.
The biggest advantage of using custom tags is that our program code is concentrated in one place (for Java technology, generally in the "class"), which is easy to manage. In this way, the integration relationship between the Object layer and the interface layer in the program can be clearly defined, and the impact of code modification can be predicted and managed.
Another way to directly convert XML data into Web display content is to use XSL and XSLT. In this solution, the logic for ing XML data to HTML (or WML) is defined by the XSL style sheet (XSL stylesheet. A style sheet describes how to convert a specific XML data entity to an interface data entity (such as an HTML table or an inline tag ). In JSP architecture, XSL conversion can only be applied to specific XML data sources. Ideally, a custom JSP tag is used to reference An XSLT processing program. For typical examples, see the whitepaper on XML integration with JSP architecture in java.sun.com.
Compared with the preceding JSP custom tag plus XML Parser component scheme, the XSLT scheme has better scalability and better manageability. In this case, our conversion logic is written in an XSL style sheet, rather than in Java code. This means that when you need to modify the interface, you can only edit the style sheet or HTML in most cases, and the code is not affected. However, we should carefully weigh the options based on the actual situation. If you use the XSLT scheme, someone has to maintain these XSL style sheets (either the person responsible for the interface or the person who compiled the program ). XSLT is like content and a program. Therefore, neither party can push the responsibility to the other party. As a result, everyone may be confused by this nondescribable XSLT. In this regard, it seems more attractive to use custom tags and the interface developers can embed them into the presentation layer, because in this way, software engineers only consider Java code, content engineers only care about content labeling.
Java Servlet filter is a Web component recently released on the web layer of J2EE 1.3. When sevelet writes a request to a resource or reads the answer information from a resource, the filter can easily convert the header information and content information. The resources mentioned here can be a Java Servlet, a JSP page, or even a static Web page. The filter is really cool, because it allows developers to separate and reuse the part of the Code that was born into content from the code that converts the content. The Java Servlet filter is particularly useful when XML data needs to be converted to different XML application targets through XSLT.
Use the Java Servlet filter in a J2EE application to convert its output, so as to be compatible with the foreground of any type of client. Servlet filters can detect calls from mobile clients that use the WAP protocol (Wireless Application Protocol) and convert the response content to the WML format. Servlet filters can also detect calls from imode wireless customers and convert them into chtml (compact html) formats. Of course, Servlet filters can also identify requests from traditional HTML browsers and reply in the correct format.
Conclusion
In the J2EE 1.2.1 specification, XML "integration" only refers to the deployment description of components or applications in XML format. In the J2EE 1.3 specification, XML support is extended to require a sax 2 and Dom 2 parser, and An XSLT conversion handler is provided on a J2EE-compatible server platform. You can undoubtedly believe that more XML features will be incorporated into the J2EE architecture in the future, because the J2EE standards will be well understood by developers who are eager to use more XML in enterprise-level applications. For example, part of the JSR (Java-defined request) processing team related to the jaxm specification (JSR 000067) promises to integrate jaxm in subsequent J2EE specifications. It is foreseeable that similar changes will occur in the JSP architecture, EJB, and JDBC specifications. The above Component Changes on the J2EE platform will make the XML currently used by Java developers more standardized.