About the Author
Xue Guyu is Nordsan (Beijing) Information Technology Development Co., Ltd. Is committed to the development of server products for enterprise-level heterogeneous data exchange. It has a relatively rich development experience in J2EE and Web Service, you can pass Rainight @ 126.com got contact with him.
Foreword
AXIS is the SOAP engine launched by Apache, and the AXIS project is a successive project of Apache's famous SOAP project. AXIS provides developers with a large number of serialization / reverse sequencer, which can basically meet most of the applications. However, in some cases, the existing sequence / reverse sequencer cannot be competent for specific objects, so only the developer's own sequence-based / anti-sequencer is inserted into the AXIS to complete the sequence. Work. Considering that Web Service is an emerging technology, most Chinese materials are generally explained, and the development of sequential / anti-sequencer is a relatively in-depth introduction, this article provides a more complete development guide, and provides a very Useful implementation, Element of the serialization JDOM model, so that it can be transmitted over the web through the web service, I think this extension is the function of many developers who use JDom as a developer who uses JDom as an XML parsing tool. Through the introductions and examples of this article, it is desirable to play the role of tipping jade. The reader can easily achieve the serialization / reverse sequencer for any non-compliant bean specification after reading this paper.
The readers in this article need to have certain development experience using AXIS to develop Web services, so the basic knowledge of Axis is not in this paper, if the reader is interested, you can refer to the final reference part of this article. Go to the corresponding website for learning.
Profile
The corresponding translation of serialization / reverse sequencer is Serializer / Deserializer, a serializer functionality is to follow a certain mapping rule and coding style, and a type of Java object is converted into a specific mechanism. XML description form; the function of the reverse sequencer is the reverse operation of the serializer, and the two are complementary, and there is a pair. The serialization / reverse sequencer in AXIS uses factory modes in the design paradigm, each of which corresponds to a serializerfactory; each Deserializer is the only deserializerFactory. One type of Java object is specifically used which serialization / reverse sequencer needs to provide a web service server and client that calls the web service, how to configure this part, I will make detailed in the content later in this article. Introduce. Axis has provided developers with a rich serialization / reverse sequencer, for the basic data type of Java, most commonly used container classes (such as array types, vector types, etc.) provide implementation, especially W3C's DOM object (such as Document, Element et al.) And the Java object compliant with the bean specification provide a perfect serialization / reverse sequencer, so we can use it directly in the configuration file when needed. If the object contains other types of objects, such as a set of bean objects, AXIS automatically overlap the serializer, and finally assembled into unique XML representations. When restoring into a Java object, it is also followed by reverse operation. Regarding which serialization / reverse sequencer in the AXIS, you can refer to the name "Wang Wenshan" in the package of the class in the AXIS 'API document, and the next development in the future development. There are countless in your heart. But for some special types of objects (in fact, the big part of our own development is this special type of object, very few in line with the bean specification), you need to pass the web service, we have to develop your own sequence Chemical / reverse sequencer.
Development articles
Developing your own serialization / reverse sequencer is an exciting job, but it is not complicated, what you need to do is to achieve serializerfactory, Serializer, Serializer, DeserialIzerfactory and Deserializer, De implementing the name of Org.apache.Axis.Encoding. Four interfaces. Below I will explain the development of the sequence / resequent sequencer, and I hope the reader can learn from the source code provided herein.
As a comparative "alternative" XML parsing tool (because it does not conform to the W3C DOM model, it is a set of separately, silently occupying the half-waters of the XML parser in the Java world, due to its simple design and convenient flexibility The API call has gradually become the first choice for many developers in XML development. But AXIS is based on the DOM model of W3C. The teacher is famous, naturally disdain and JDOM. Therefore, when the developer wants to publish the JDOM-based application module to the web service, it is inevitable to encounter the problem of how to make the object under the JDOM model such as Document, Element, etc. When the software engineer does not extend the serialization / reverse sequencer of the AXIS, we can only have two ways to achieve this, the first is to change the API design in the previous application module, so that the exposed entrance parameters and return The value parameters are the type of W3C, but this approach is not realistic, because this application module is often not independent, and it will move the whole body, leading to the collapse of the old system architecture; another approach is for this module Be a proxy class, which receives or returns an object of the DOM model, and converts it to the object of the JDOM model, and then forwards to the application module, cumbersome and low efficiency. When we injects the serialization / anti-sequencer for the JDOS model to AXIS, this work can be handled by Axis. Below we will develop these four classes one by one:
JDOMELEMENTSERIALIZERFACTORY
JDomelementSerialIzerFactory is a factory class that needs to be registered to the AXIS engine through a mechanism (see "Server Application" below); Axis is instantiated by calling it to instantiate the JDomelementSerializer. AXIS provides BaseSerializerFactory, which is an abstract class and implements some reusable code. The factory class we have developed by our own can only inherit this class. The constructor is required to call the parent class to the sequencer class below its source code:
Package org.apache.axis.encoding.ser;
Public Class JDomelementSerializerFactory
Extends baseserializerfactory {
Public JDomelementSerializerFactory () {
Super (JDomelementSerializer.class);
}
}
JDOMELEMENTSERIALIZER
JDOMELEMENTSERIALIZER implements org.apache.axis.encoding.Serializer interface, its core API is serialize (), we need to complete the serialization of Element for the JDOM model internally, and serialized results to be saved in the entrance parameters Serialization Context Object (SERIALIZATIONCONTEXT):
Public void Serialize (QName Name, Attributes Attributes, Object Value,
SerializationContext context) THROWS JAVA.IO.IEXCEPTION {
IF (! (value instanceof element) throw new oException
Messages.getMessage ("CANT Serialize Object")));
/ / Get the Element object in accordance with JDOM
Element root = (element) value;
// Output to StringWriter
XMloutPutter Outputter = new xmloutputter (); // Create a JDOM's XML outputter
StringWriter SW = new stringwriter ();
Outputter.output (root, sw);
// resolve text streams with Xerces parsers that support W3C's DOM model
DOMPARSER PARSER = New DOMPARSER (); // Create a DOM's XML parser
Try {
Parser.parse (new org.xml.sax.inputsource
New java.io.stringReader (SW.TOSTRING ()))))))))
} catch (exception ex) {
Throw new java.io.ioException ("Errors when serialization");
}
/ / Get the ELEMENT object that meets the DOM model
Org.w3c.dom.Element W3C_Root =
Parser.getdocument (). getDocumentelement ();
// put in the serialization context object
Context.startElement (Name, Attributes);
Context.writeDomelement (w3c_root);
Context.enDelement ();
}
JDOMELEMENTDSERIALIZERFACTORY
The factory class of the factory class of the deserialization is the same as the factory class of the factory, hereby not to Code:
Package org.apache.axis.encoding.ser;
Public Class JDomelementDeserialIzerFactory
Extends basedeserializerfactory {
Public JDOMELEMENTDESERIALIZERFACTORY () {
Super (JDOMELEMENTDESERIALIZER.CLASS);
}
}
JDOMELEMENTDSERIALIZER
Used SAX analysis of XML readers, it is more likely to understand the re-sequence-based implementation, and the anti-selecente is also used to trigger the mechanism, we only need to inherit the org.apache.axis.encoding.deserializerImpl class, and override the OneIndelement method :
/ **
* End Trigger Deverse Deserialization Method
* @Param Namespace String Namespace
* @Param localname String Local name
* @Param Context DeserizationContext Declined Context
* @throws saxException
* /
Public void Onendelement (String Namespace, String Localname,
DeserializationContext context) throws saxexception {
Try {
/ / Get the original message element from the reverse sequence context object
MessageElement msgelem = context.getcureLEMENT ();
IF (msgelem! = null) {
MessageContext.getMessageConText ();
Boolean currentelement = (boolean) messagecontext.getProperty (DeserialIze_current_element);
// If the current message element itself needs anti-sequence
IF (Currentelement! = null && currentelement.booleanvalue ()) {
Org.w3c.dom.Element Element = msgelem.getaSdom ();
Org.jdom.input.Dombuilder db = new org.jdom.input.Dombuilder ();
Value = db.build (element);
MessageContext.SetProperty (DeSerialize_current_element,
Boolean.false;
Return;
}
// Message body in the reverse sequence of message elements
Java.util.ArrayList Children = msgelem.getchildren ();
IF (children! = null) {
// get the message body
MsGeleM = (MessageElement) children.get (0);
IF (msgelem! = null) {
Org.w3c.dom.Element Ret = msgelem.getaSdom ();
Org.jdom.input.Dombuilder db = new org.jdom.input.Dombuilder ();
// convert the Element of the DOM model into the ELEMENT of the JDOM model with DomBuilder
Value = DB.BUILD (RET);
}
}
}
}
Catch (Exception EX) {
/ / Error, then log, and throw SAXException
LOG.Error (Messages.getMessage ("Exception00"), EX);
Throw new saxexception (ex);
}
}
Complete these four codes, the development of serialization / reverse sequencer is basically completed, and the use and deployment methods will be explained in detail below.
Server application articles
For the sake of simplicity, we will release a very simple class through the Web service, only one name in the class is a Hello function, the return value of the function is the ELEMENT of the JDOM model. code show as below:
Package test;
Import Org.jdom. *;
Import java.rmi.remoteexception;
Public class Sample1 Implements java.rmi.remote {
Public Sample1 () {
}
Public element hello (string name) {
Element root = new element ("root");
Element Hello = New Element ("Hello");
Hello.setText ("Hello," Name "!");
Root.addContent (Hello);
Return root;
}
}
Regarding how to release a class into a web service, this is not introduced here, I believe that the reader can do itself, we only pay attention to how to add a serialization / anti-sequencer to our web service. Open the configuration file server-config.xml of the web service, edit the configuration section of the service of Sample1:
EncodingStyle = "http://schemas.xmlsoap.org/soap/encoding/" QNAME = "ns1: element" LanguagespecificType = "java: org.jdom.element" Serializer = "Org.apache.axis.encoding.ser.jdomelementSerializerFactory" Deserializer = "Org.apache.axis.encoding.ser.jdomelementdeSerializerFactory" Name = "element" regenerateElement = "true" XMLns: ns1 = "http://jdom.org" /> service> Note that the bold part of the above code is what we are now added, which shows how to deploy the serialized anti-sequencer into the web service. Deploy to Web Server Unzip the source code supplied with this article, there is a build.xml file in the root directory, readers need to properly install the APACHE ANT, then run Ant Make After compiling, the compressed file Sample.war can be generated. Deploy the generated WAR package to Tomcat4.1, start Tomcat, the default Tomcat listener of this article is 8080. The later client test program will also access this web service by connecting this port. If the reader's Tomcat is not working on the 8080 port, the client program also has the corresponding modification. Finally launch Tomcat, this part of the operation is complete. Client application articles Below we will write client programs to access the Web services that just deployed, explain how to write our serialization / reverse sequencer into the client application, the following is the code of the client call, pay attention to the oblique part, is about Serialized / Anti-sequencer registration process (if your web server is not working at 8080 port, or uses other web service names, change the value in the URL variable in the following program), we create under the TEST package A class named Client, the code is as follows: Package test; Import org.apache.axis.client.service; Import org.apache.axis.client.call; Import org.apache.axis.utils.options; Import javax.xml.namespace.qname; public class client { Public client () { } Public static void main (string [] args) throws exception { IF (args.length <1) { System.out.println ("Error: Missing Parameters); System.exit (0); } // Web service URL String Url = "http: // localhost: 8080 / sample / service / sample1"; Service service = new service (); Call call = (call) service.createcall (); Call.SetTargetendPointDress (URL); // Register serialization / reverse sequencer Call.registerTypemapping (Org.jdom.element.class, New Qname ("http://jdom.org", "element"), New org.apache.axis.encoding.ser.jdomelementSerializerFactory (), New org.apache.axis.encoding.ser.jdomelementdeSerializerFactory ()); // Set the call method Call.Setoperationname New javax.xml.namespace.qname ("http:// Test", "Hello"); // Web service call Java.lang.object _resp = call.invoke (new java.LANG.Object [] {args [0]}); // Output to the screen Org.jdom.Output.xmloutputter out = new org.jdom.output.xmloutputter (); Out.output ((org.jdom.element) _resp, system.out; } } After compiling, enter the program, enter the root of the console window project. Run World (where "World" is the entry parameter of the API in the call routine) After a web communication, the screen will be displayed in the screen after a two second: root> At this time, we have completed the access process of a web service. If we use TCP Moniter, we can see the XML data stream that is called in the network with tools in the program execution. Post / Sample / Services / Sample1 HTTP / 1.0 Content-type: text / xml; charSet = UTF-8 ACCEPT: Application / SOAP XML, Application / Dime, Multipart / Related, Text / * User-agent: AXIS / 1.1 Host: 127.0.0.1 Cache-Control: No-cache Pragma: no-cache SOAPACTION: "" Content-Length: 430 XML Version = "1.0" encoding = "UTF-8"?> "http://schemas.xmlsoap.org/soap/Envelope/"xmlns:xsd="http://www.w3.org/2001/xmlschema" XMLns: xsi = "http://www.w3.org/2001/xmlschema-instance"> "http://schemas.xmlsoap.org/soap/encoding/" XMLns: ns1 = "http:// Test"> ns1: hello> soapenv: body> soapenv: envelope> The XML output stream of the result returned by the server side is as follows: HTTP / 1.1 200 ok Content-type: text / xml; charSet = UTF-8 Date: WED, 31 Mar 2004 06:42:18 GMT Server: Apache Coyote / 1.0 Connection: Close XML Version = "1.0" encoding = "UTF-8"?> "http://schemas.xmlsoap.org/soap/ENvelope/" XMLns: xsd = "http://www.w3.org/2001/xmlschema" XMLns: xsi = "http://www.w3.org/2001/xmlschema-instance"> "http://schemas.xmlsoap.org/soap/encoding/" XMLns: ns1 = "http:// Test"> ns1: helloresponse> "http://schemas.xmlsoap.org/soap/encoding/" XSI: Type = "NS2: Element" XMLns: sopenc = "http://schemas.xmlsoap.org/soap/encoding/" XMLns: ns2 = "http://jdom.org"> root> MULTIREF> soapenv: body> soapenv: envelope> Conclusion The above-described development process of the serialization / anti-sequencer is explained in detail, and believe that readers have become a lot of knowledge from the middle school and can be applied to their project development. By mastering this technology, we will understand the internal structure of AXIS and the work of WEB services. These experiences are not learned in the market. Subsequent articles will also show you some advanced technologies in Java Web service depth development, so that you really control AXIS. Reference All source code in this article is provided in the annex. It is a complete project that can be referred to. In Apache's website you can get the latest AXIS library and its development document: http://ws.apache.org/AXIS/ The Tomcat web server mentioned herein is available here: http://jakarta.apache. Org / Tomcat / INDEX.HTML "IBM Developwork" Tutorial about Web Services "Creating a Web Service from Java Class" is a very good textbook that you quickly master the development of Web services, beginners can learn. The JDOM class library can go to www.jdom.org download, and there is a good article on 9CBS to allow you to quickly master the use of JDom. http://www.9cbs.net/develop/read_article.asp?id=13806