Web Service Learning Notes ---- JAX-RPC

zhaozj2021-02-16  44

Web Service Learning Notes ---- JAX-RPC

In this paper, this article is the finishing of the notes made when learning JWSDP-1.2, which is mainly some guided content, and there is not much concept and principle. Readers may feel slightly simple. If you want to learn basic concepts, you can refer to the Internet. Information about Web Service. The development environment used in this article is WindowXP JWSDP-1.2.

One. Introduction to Web Service 1. Define the basic communication protocol between two parts composed of SOAP - Web Service. · WSDL - Web Service Description Language, which defines what Web Service does, how to do and query. 2. Simple Web Service implementation contains four basic steps · Creating a web service business logic (usually some Java classes) • Deploy these Java classes to a SOAP server · Generate customer access code · Deploy customer application Note: WSDL, etc. The generation of files is usually used to complete the tools provided by the vendor. 3. WSDL parsing WSDL Description Language typically contains three parts · what section - includes Type, Message and PortType element TYPE: Define the data structure used by Web Service (using XML Schema Definition) Message: A message is the basic communication element of SOAP. Each Message can have one or more parts, each Part represents a parameter. PortType: The message is summarized as different operations and is classified into an entity called PortType. A porttype represents an interface (a collection of the web service support), each Web Service can have multiple interfaces, which are represented by PortType. Each operation also includes an Input and Output section. · How section - Contains Binding Elements Binding Elements Bind PortType to specific communication protocols (such as SOAP protocols on HTTP) · WHERE section - Composition from Service Elements It puts PortType, Binding, and Web Service Location (URI) Put together to describe 4. Client usually Web Service can have three types of customers · Business Partner - including distributors, retailers, and large consumers) such customers via SOAP, WSDL, EBXML, UDDI, etc. XML Technology and Web Service Connection • Thin Customers - including web browsers, PDAs, and wireless devices, usually via lightweight protocols, such as HTTP, and Web Service, Fee customers, including applets, various applications, and existing systems Usually use a heavyweight protocol (such as IIOP) to connect Web Service

2. Develop Web Service1 using JAX-RPC. JAX-RPC supported data type JAX-RPC supports some custom objects in addition to supporting Java's basic data types, but these objects have some conditional restrictions • Objects with default constructor · No Java.Rmi.Remote interface Fields must be the type of JAX-RPC support. The public field cannot be declared as Final or Transient • Non-public fields must have a corresponding setter and getter method 2. Create Web Service · Basic Step A using JAX-RPC. Writing a server interface and implementing an end-point for a service: a java.rmi.Remot interface must be implemented and each method needs to throw RemoteException. B. Compile, generate and package all the services needed by all services into the WAR file C. Deploying the WAR file containing the service • How to create a service A. Compile the class file B. Generating a service The required file can use the WSCompile tool to generate the model.gz file, which contains the internal data structure command for the service command, wscompile -define -d build -nd build -classpath build config.xml -Model build / model.gzdefine flag tells Tool read the EndPoint interface of the service and create a WSDL file. -d and -nd flag tells the tool to write the output file to the specified directory building.

Tools need to read the following config.xml file The file tells WSCompile to create the information required to create a Model file. Service Name: MyHelloService · WSDL Name Space: URN: Star · HelloService All classes of HelloService (endpoint) interface: HelloService.Helloifc. Package the service to WAR files Web-inf / class / hello / helloif.classweb-inf / classweb-inf / jaxrpc-ri.xmlweb-inf / model.gzWeb-inf / web.xmljaxRPC-RI. The XML file is as follows d. Processing the WAR file Using the command line WSDeploy -o hello-jaxrpc.war Hello-jaxrpc-original.warwsDeploy tool Complete the following tasks • Read Hello-Jaxrpc-Original.war as input · Get ​​information from JAXRPC-RI.XML files · Generate TIE CLASSES for the service to generate WSDL files named HelloService.wsdl • Pack Tie Classes and HelloService.WSDL files into a new WAR file E. Deploy service on the server If you use Tomcat, you can copy the WAR file into the webapps directory, then you can see if you have successfully configured on

Static Stub, Dynamic Proxy and Dynamic Invocation Interface (DII) Static Stub Stub generated by using client-config-wsdl.xml and wscompile tool that can generate stubwscompile -gen: client -d build -classpath build config-wsdl.xml config-wsdl The .xml file is as follows < WSDL Location = "http: // localhost: 8080 / hellow / hello? WSDL" packagename = "staticstub" /> WSCompile tool reads the WSDL file on the server and generates stub · Write static customer code stub stub = Stub) (new helloifport (); getHelloifport (); helloif hello = (Helloif) stub; hello.sayhello ("starchu"); Note: HelloService_Impl class is generated by WSCompile · Compile Code • Run client (need to include Saaj API and JAX-RPC API Run) Dynamic Proxy Customer · Generate Interface By using config-wsdl.xml files and WSCompile tools, you can generate the interface WSCompile -import -d build -classpath build config-wsdl.xmlconfig-wsdl.xml required by customers. The file content listed above is the same. · Writing Dynamic Customer Code ServiceFactory Factory = ServiceFactory.newInstance (); URL WSDLURL = New URL (""); Service Service = Factory.createService (WSDLURL, New QNAME ("URN: Star", " Helloservice "); Helloif Hello = (Helloif) Service.getPort (New QNAME (" URN: Star "," Helloifport "), Helloif.class; Hello.Sayhello (" starchu "); Note: This no longer needs static HelloService_Impl class · Compile Code • Run the client (need to include Saaj API and JAX-RPC API Run) Dynamic Invocation Interface Customer This method provides us with more flexible customer call mode, customer code is not required by WSCompile tools The runtime class, of course, this code is more complicated. The specific steps are as follows: • Create a ServiceFactory instance serviceFactory factory = servicefactory.newinstance (); • Create service (using service name QNAME) service service = factory.createService ("HelloService");

· Create a Call object (QNAME using the endpoint interface) Call call = service.createcall ("Helloif");

· Set the address and endpoint number Call object attributes call.setTargetEndpointAddress (args [0]); call.setProperty (Call.SOAPACTION_USE_PROPERTY, new Boolean (true)); call.setProperty (Call.SOAPACTION_URI_PROPERTY, ""); call.setProperty ("Javax.xml.rpc.encodingstyle.namespace.uri", "http://schemas.xmlsoap.org/soap/encoding/"" • Set the return type, opera name and parameter QName StringType = New QNAME ( "Http://www.w3.org/2001/xmlschema""" ") Call.setReturntype (StringType); Call.Setoperationname (New QNAME (" URN: Star "," Sayello "); Call.AddParameter "String_1", StringType, ParameterMode.in;

· Call the invoke method string [] param = {"starchu"}; string return = call.invoke (param);

· Compile the code and set

3. Examples of SOAP Message Handler typically use JAX-RPC to create Web Service does not require developers to handle SOAP messages, but JAX-RPC provides a mechanism to make programmers to get this processing power. This is called message processor. . In general, like logs and cardiac features can be implemented through the SOAP message processor, in addition to this, you don't need to handle SOAP messages at all. · Basic Handler Process Soap Request • The client processor is called before the request message is sent to the server before the request message is distributed to the end point before the endpoint is called the SOAP answer. The server processor is sent back to the customer before the response message. Calling • The client processor is called before the response message is converted to the Java method to return to the SOAP error handling process. Note that the processor can form a processor chain A in any end. Handler Basic Programming Model Services • Write a Service End Point Interface Code, implementing service and implementing server processor classes • Create a JAXRPC-RI.XML file so that WSCompile is used, which contains Handler information • Create a web.xml file · Compile all Code • Pack the file to WAR files • Replace the original WAR file with the WSDeploy tool to completely deployed WAR files • Deploy the WAR file client on the server · Write a client and client processor code · Create a config.xml file WSCompile uses, it contains information about the client processor. Compile Code • Run WSCompile Generate Service End Point Interface and Customer Class · Compile all code, and run customer application

B. Establishing a client processor processor must extend the javax.xml.rpc.handler.GenericHandler class and provide at least two ways to implement init and getHandlers. In addition, you can use the Handlexxx method to process requests, answers, and error SOAP messages.

The basic steps are as follows. Write client processor code Public class ClientHandler extends GenericHandler {Public void init (HandlerInfo info) {This.info = info;} public QName [] getHeaders () {return info.getHeaders ();} public boolean handleRequest (MessageContext context) {SOAPMessageContext smc = (SOAPMessageContext) context; SOAPMessage message = smc.getMessage (); file: // You can use SOAP API to implement your own logic file: // such as logging and encrypt ...... file: / / Set a logger element in the SOAPHeader SOAPHeaderElement loggerElement = header.addHeaderElement (envelope.createName ( "loginfo", "ns1", "urn: Star: headprops")); loggerElement.setMustUnderstand (true); loggerElement.setValue ( "10 "); file: // Set a name element in the SOAP Header SOAPHeaderElement nameElement = Header.addHeaderElement (envelope.createName (" client "," ns1 "," urn: Star: headprops ")); nameElement.addTextNode (" Star Chu ");}} · Edit config.xml file • Write static customer C. · Preparation of the establishment of the server processor server processor (similar to the client-side structure) Public boolean handleRequest (MessageContext context) {SOAPMessageContext smc = (SOAPMessageContext) context; ...... Iterator it = header.examineAllHeaderElements (); While (it.hasNext ()) {SOAPELEMENT Element =

() Ney () {Element.getValue (); element.detach (); file: // invoke online}}}}} Detach method Used to remove the element, this requirement is only necessary when an element is set. · Edit JAXRPC-RI.XML file in the first processor, XML uses the property headers description header information. This is because the customer code tells the server, the logger header must be understood, otherwise the customer will receive the SOAP error message to generate the WAR file and deploy it to the server 4. Source code · Helloif.java (endpoint interface) package helloservice; import java.rmi.RemoteException; import java.rmi.remote

Public Interface Helloif Extends Remote {Public String Sayhello (String Target) Throws RemoteException;} · HelloImpl.javaPackage HelloService

public class HelloImpl implements HelloIF {private String message = "Hello"; public String sayHello (String target) {return message target;}} · StaticClient.javapackage staticstub; import javax.xml.rpc.Stub; public class StaticClient {private static String endpointaddress; public static void main (string [] args) {if (args.length! = 1) {system.err.println ("Usage: java helloclient [endpoint address); system.exit (-1); } endpointAddress = args [0]; System.out.println ( "Connect to:" endpointAddress); try {Stub stub = createStub (); stub._setProperty (javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, endpointAddress); HelloIF Hello = (Helloif) stub; system.out.println (Hello.Sayhello ("starchu!"));} catch (exception e) {system.err.println (e.tostring ());}} private static stub createstub () {return (Stub) (new HelloService_Impl () getHelloIFPort ().);}} · DynamicClient.javapackage dynamicproxy; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.rpc.Service Import javax.xml.r pc.ServiceFactory; import javax.xml.rpc.JAXRPCException; import staticstub.HelloIF; public class DynamicClient {private static String wsdl; private static String namespaceUri = "urn: Star: wsdl"; private static String serviceName = "HandlerService"; private Static string portname = "handlertestport";

Public static void main (string [] args) {if (args.length! = 1) {system.err.println ("usage: java dynamicclient [server url)); system.exit (-1);} system. Out.println ("Connect TO:" args [0]); HellowsDL = args [0] "? WSDL"; try {url wsdlurl = new url (WSDL); servicefactory servicefactory = serviceFactory.newinstance (); service service = serviceFactory.createService (wsdlUrl, new QName (namespaceUri, serviceName)); HandlerTest proxy = (HandlerTest) service.getPort (new QName (namespaceUri, portName), HandlerTest.class); proxy.test ();} catch (Exception e ) {System.err.println (e.toString ());}}} · DIIClient.javapackage dii; import javax.xml.rpc *;. import javax.xml.namespace *;. public class DIIClient {private static String qnameService = "HelloService"; private static String qnamePort = "HelloIF"; private static String BODY_NAMESPACE_VALUE = "urn: Star"; private static String ENCODING_STYLE_PROPERTY = "javax.xml.rpc.encodingstyle.namespace.uri"; private static String NS_XSD = " http://www.w3.org / 2001 / xmlschema "; private static string uri_encoding =" http://schemas.xmlsoap.org/soap/encoding/ ";

public static void main (String [] args) {try {ServiceFactory factory = ServiceFactory.newInstance (); Service service = factory.createService (new QName (qnameService)); QName port = new QName (qnamePort); Call call = service. createCall (port); call.setTargetEndpointAddress (args [0]); call.setProperty (Call.SOAPACTION_USE_PROPERTY, new Boolean (true)); call.setProperty (Call.SOAPACTION_URI_PROPERTY, ""); call.setProperty (ENCODING_STYLE_PROPERTY, URI_ENCODING) ; QName qnameTypeString = new QName (NS_XSD, "string"); call.setReturnType (qnameTypeString); call.setOperationName (new QName (BODY_NAMESPACE_VALUE, "sayHello")); call.addParameter ( "String_1", qnameTypeString, ParameterMode.IN) String [] params = {"starchu"}; system.out.println ((String) Call.invoke (params));} Catch (Exception E) {system.err.println (E.TOSTRING ());} }} · ANT file build.xml

< / Target>

· Property file (build.xml file usage) server = c: /java/jwsdp 1.2/webappstomcat.home=c: /java/jwsdp 1.2ndPoint=http: // localhost: 8080 / hellows / helloserver .port.url = http: // localhost: 8080 / hellows / hello

Reference 1. Developing Web Service Series www.theserverside.com2. JWSDP-1.2 Tutorial java.sun.com

Disclaimer: If you need to repost, please indicate the source

转载请注明原文地址:https://www.9cbs.com/read-26870.html

New Post(0)