The perfect combination of XML and Java EE

Source: Internet
Author: User
Tags filter format define definition end error handling header object model
J2ee|xml Currently, the Java 2 Platform Enterprise Edition (Java EE) architecture is highly respected in the vendor market and the developer community. As a tool, Extensible Markup Language (XML) simplifies data exchange, interprocess messaging, and thus becomes attractive to developers and is becoming popular. Naturally, the idea of accessing or integrating XML solutions in the Java EE architecture is also tempting. Because it will be a combination of a strong system architecture and a highly flexible data management solution.   XML applications seem to be endless, but they can be broadly divided into three broad categories:   Simple data representation and exchange (for XML Simple API (SAX) and Document Object Model (DOM) syntax parsing, Different document type definitions (DTDs) and Profiles (schemas))   Message-oriented computing (XML-RPC (remote procedure Call), SOAP protocol, Electronic Business XML (EbXML))   user interface related, Represents a related context (Extensible Stylesheet Language (XSL), Extensible Stylesheet Language Transformation (XSLT))   These types of applications have a natural counterpart in the Java EE Architecture: Data representation and switching functions are persistent services in the EJB component model (persistence  Services), a message based communication is handled by the Java Messaging Service (JMS) API, and interface representations are the forte of Java Server Pages (JSP) and java servlets.   In this article, we will see how XML is applied in these areas in today's Java based applications, and how these applications will evolve in future versions of the relevant standards.   Fundamentals: Data representation and exchange   prototyping XML applications (if any) are usually content: data is stored in XML format and is often read into an object model in order to display, modify, or even write to an XML document. As an example, suppose we are dealing with multiple types of media (graphics, video, text documents, and so on), and use the following simple xml dtd 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) >     Below is an XML document based on the above media DTD that describes the content associated with a course lecture:  <?xml  Version= "1.0"  ?><! doctype media-asset public  "-//jim farley//dtd   Media Assets//EN"   " Http://localhost/Articles/Sun/dtds/media.dtd ">  <media-asset>  <name> 14th lecture </name>   <desc> all content related to the 14th lecture </desc>  <!--  Content Object "Lecture 14" a set of subcomponents  -->   <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> Lecture video clips </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>  <!--  Lectures start  -->  <urn>http:// javatraining.org/jaf/e123/lecture-14/index.jsp</urn>  </media-asset>   In terms of Web or enterprise-level applications, access to data in this way is a boon, because it embodies a high degree of mobility that separates us from the actual resources of the metadata itself. These resources may come from a relational database system, an active media server, or a static XML document on a Web server, and so on. If you want to load this data into Java applications, we canTo choose from the current multitude of Java language XML parsers, it loads XML data into a DOM document, finally traverses the document, and converts all of that data into the object model of our application system.   Below is a simple DOM-based parser that resolves the above media dtd. The parser is   apache xerces:     package jaf.xml;  import java.util.*;  import java.io.ioexception;  import org.w3c.dom.*;  import org.xml.sax.*;     // xml Document Resolver using the above media dtd.  Public class mediaparser implements errorhandler  { /**  using apache xerces parser  */  Org.apache.xerces.parsers.domparser mparser  =   new org.apache.xerces.parsers.domparser (); /**  constructor  */  Public  mediaparser ()  { //  tells the parser to validate 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 parser error handling handle   Mparser.seterrorhandler (this); }  parse the specified URL. Returns the XML document found   */  public document parse (string url)  throws SAXException,  ioexception {  mparser.parse (URL);  document mediadoc = mparser.getdocument ();   return mediadoc; } /**  resolves XML documents that specify URLs and converts content to  MediaAsset  objects   */  Public collection loadassets (string url)  throws SAXException,   IOException  {  document doc = parse (URL);  collection assets = new  LinkedList ();  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 brevity)   *  */  The constructor of the Mediaparser class initializes a xerces dom parser. The parse () method tells the parser which URL to look for the XML source, and then gets the resulting document and returns. The Loadassets () method calls the parse () method to load the document from an XML source and then creates a Mediaasset object for each "Media-asset" node found in the document.   Below is an example using the Mediaasset class:  package jaf.xml;  import java.util.*;  public class  MediaAsset { //  resource meta data   private string mname =  "";  private  String mDesc =  "";  private collection mchildren = new  LinkedList ();  private vector mtypes = new vector ();  private String  mUrn =  "";  protected mediaasset (Org.w3c.dom.node assetnode)  { //   Omit the following code for brevity   .  .  . } }  The detailed code for the Mediaasset class is omitted because of the length of the relationship, but the application pattern is still clear. The Mediaasset class traverses the node of the document and, when it encounters a different child node, populates its own member data with the contents of its child nodes. If it finds a nested child resource node, it only needs to create a new mEdiaasset the object, and then populates the child resource node's data into the new object's member data.   There are countless ways to achieve the above treatment. We can also use other parsers or parser schemas, such as java api for xml parsing  (JAXP). In addition to using the DOM model, event-driven sax models can also be used to parse XML. Similar programs can also be used to produce XML data--provided that a new data object is allowed (in this case mediaasset), it can insert its corresponding XML entity into the DOM, and then output the DOM to a stream (such as a file, a socket, or an HTTP connection ... )。 There are other higher-level criteria for further automation (or simplification) of the process of mapping XML to Java objects. For example, using the XML overview (Schema) and the XML binding processing engine, you can semi-automatic the transformation of XML data that satisfies a xml  profile into a Java data object. The representative engine is Castor, a product of an open source project managed by the Exolab team. The above simple example of using Xerces dom is simply a demonstration of the underlying model of this process.   The above example shows that it is very convenient to parse or produce XML in the Java environment, which is not necessarily associated with EE. Data formatted as XML can be streamed or exported from any level of the application, making the integration with external Systems unlimited. But can we integrate XML data sources into the Java EE architecture in a more straightforward way?   Control Message   Java architecture includes access to the JMS (java-based messaging) APIs to enable message-oriented communication (j2ee 1.2.1 version only Jms api, in j2ee  1.3 Version of JMS Basic stereotypes, at this time must be a compatible Java platform server to provide a jms api provider. This type of asynchronous interaction (in contrast to the synchronous interactions represented by local or remote method calls) is proven to be useful in some application environments. At some point, the interaction only needs to be done through an indirect request or answer, that is, in some cases it is not possible to receive a response immediately after the message is sent, but we still want to make sure that he receives a reply when the message is sent back online. One of the practical applications of the   message-oriented system is the loose integration between enterprises. Similar to the EDI (electronic document exchange) era of document exchange, two enterprises because of the business needs of the exchange of messages, at this time is usually not in order to use RPC or RMI, CORBA, DCOMRemote methods like this, and they are tightly integrated between the two. A message system such as JMS&NBSP;API allows both parties to exchange JMS&NBSP;API message loads on the premise that both parties can provide compatible JMS&NBSP;API services at the time of the session. The current difficulty is whether the two sides can respect the same format or agreement.   That's when XML is doing its thing. XML is explicitly designed to solve such data-exchange problems-the panacea is the "message-Oriented summary table" (Message-oriented communication scheme), The essence is to Exchange message loads in XML format based on a mutually agreed DTD or schema. The   JMS&NBSP;API supports several kinds of messages, where the textmessage represents the text message payload. A simple and efficient XML message exchange scheme is to insert our XML document into the TextMessage at one end and then, at the other end, unpack the data with a homemade XML parser (such as the previous mediaparser) and convert it (optionally) into a Java object. This allows us to either use the publicly subscribed message model supported by JMS&NBSP;API, or to send XML messages using the point-to-point message model supported by JMS&NBSP;API.   The above methods have some limitations because the content of the XML is essentially opaque to JMS run-time processing. For example, JMS&NBSP;API allows the use of routes based on a particular message header. This is easy to understand, especially when we want the XML message to take a different direction depending on its content. For example, in our Mediaasset example, we want to expose the content of the lectures, but only want to send specific content to those who have subscribed to the course, or to those who indicate that they can accept certain media formats, such as video streaming. In order to realize the value of JMS&NBSP;API in order to implement the above content-based message routing, it is necessary to parse out the key information from the XML data and then insert that information when constructing the standard JMS&NBSP;API message header. This is possible, but to implement the XML information we have to write a lot more code (both sides of the exchange message).   to bridge between XML and JMS&NBSP;API, some vendors provide custom JMS extensions to support XML message mechanisms directly. For example, the BEA WebLogic application server, which is based on Java EE, provides xmlmessage subclasses specifically for TextMessage, allowing the use of XPath expressions to filter XML messages. This is a proprietary extension, however, which requires both sides of the exchange message to be able to handle such messages.   For this reason, SuN companies are currently developing JAVA&NBSP;API (JAXM) for XML messages. The goal is to provide a high-level standard service to enable the synthesis and delivery of ebXML based messages. A JAXM service provider can map such messages to the appropriate physical message system (such as JMS&NBSP;API).   Make XML visible   integrating XML with the user interface of the web system is obviously a useful attempt. Most of the interface programs, whether based or not on the web, are transforming the data and presenting it to the user in an easy to read format. Storing data in an "digestible" format such as XML simplifies the work, and it dramatically improves the manageability of content, which we can see next. But first of all, the application of XML to the Web interface layer benefits from the development of JSP technology.   has long wanted to distinguish clearly between the presentation layer of the Web application and the underlying object model, and the JSP framework was born out of these efforts (including early jhtml attempts). The JSP framework allows you to embed Java code into HTML content so that you can implement dynamic content without constantly modifying java servlets code. The way to include Java technology in a page is through JSP tags (jsp tags), which appear in XML style. In JSPs, Java programs exist in the form of code snippets, server-side JavaBeans components, opaque tags (standard or custom) that trigger specific actions on the server side. When a user requests a JSP page through a browser, a java application Server resolves the JSP page, compiles it into a java servlet, and executes the Servlet to produce a reply page.   A way to integrate XML data sources directly into the JSP interface is to load the XML into the JavaBeans component (as we did in the Mediaasset example), and then refer to these JavaBeans components directly in the JSP.   Below is an example of embedding Java code Snippets: 

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.