WSDL and soap instances of WebService (based on Java)

Source: Internet
Author: User

Development Environment: jdk1.6 + Tomcat 6.0.18 + myeclipse6.0

The first step is to use the WSDL protocol:Xfire is used here
Xfire is a free and open-source soap framework that builds a bridge between pojo and SOA. Its main feature is to support publishing pojo as a Web service in a very simple way, the principle is that the interface reflection mechanism automatically retrieves remote methods.

WSDL is an XML language used to describe Web Services and describe how to communicate with Web Services.

Before development, please go to the official website (http://xfire.codehaus.org/Download lightning download xfire-distribution-1.2.6.zip and decompress

(1) create a web project (server) named xfirewebservice to test the WebService server.
Add the class libraries supported by xfire to the project, copy all the jar and xfire-1.2.6 in the xfire-all-1.2.6.jar lib to the project lib

(2) Load xfire to the system and add the Web. xml configuration information.

<? XML version = "1.0" encoding = "UTF-8"?> <Web-app xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" version = "2.5" xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet-Name> xfireservlet </servlet-Name> <servlet-class> Org. codehaus. xfire. transport. HTTP. xfireconfigurableservlet </servlet-class> <load-on-startup> 0 </load-on-startup> </servlet> <servlet-mapping> <servlet-Name> xfireservlet </ servlet-Name> <URL-pattern>/servlet/xfireservlet/* </url-pattern> </servlet-mapping> <servlet-Name> xfireservlet </ servlet-Name> <URL-pattern>/services/* </url-pattern> </servlet-mapping> <welcome-file-List> <welcome-File> index. JSP </welcome-File> </welcome-file-List> </Web-app>

(3) create a web service interface and declare the interface exposed by the Web Service

Package COM. test. WS; import Java. util. list;/*** <p> title: ihelloservice </P> * <p> description: define the interface </P> */public interface ihelloservice {Public String getteststring (string Str); Public exceedvo gettestobject (entervo VO); public list gettestlist (list );}

(4) create a web service implementation class to provide implementation for Web service interfaces

Package COM. test. WS; import Java. util. arraylist; import Java. util. list;/*** <p> title: helloserviceimpl </P> * <p> description: interface implementation </P> */public class helloserviceimpl implements ihelloservice {@ overridepublic string getteststring (string Str) {return "hello" + STR ;}@ overridepublic exceedvo gettestobject (entervo) {exceedvo revo = new exceedvo (); revo. setdescstr ("name:" + vo. getname () + "Age:" + vo. getage (); Return revo ;}@ overridepublic list gettestlist (list) {list <entervo> Users = new arraylist <entervo> (); For (INT I = 0; I <9; I ++) {entervo user = new entervo ("name" + I, I); users. add (User) ;}return users ;}}

(5) These two classes are specific business implementation classes, which place the specific implementation of business methods in it

Package COM. test. WS; import Java. io. serializable;/*** <p> title: entervo </P> * <p> description: input parameter object </P> */public class entervo implements serializable {Private Static final long serialversionuid = 1l; private string name; private int age; Public String getname () {return name;} public void setname (string name) {This. name = Name;} public int getage () {return age;} public void setage (INT age) {This. age = age;} public entervo (string name, int age) {This. name = Name; this. age = age;} public entervo () {}} package COM. test. WS; import Java. io. serializable;/*** <p> title: exceedvo </P> * <p> description: output parameter object </P> */public class exceedvo implements serializable {Private Static final long serialversionuid = 1l; private string descstr; Public String getdescstr () {return descstr ;} public void setdescstr (string descstr) {This. descstr = descstr ;}}

(6) Create a New META-INF folder under the src directory containing xfire/service. xml this file is the Service Release file of the xfire framework

<? XML version = "1.0" encoding = "UTF-8"?> <! -- Service publishing file --> <beans xmlns = "http://xfire.codehaus.org/config/1.0"> <service> <! -- The service tag and Its XML content provide a complete description for pojo published as a Web Service --> <Name> helloservice </Name> <! -- Unique name used when the web service is published --> <namespace> http: // test/helloservice </namespace> <! -- Namespace used for Web service publishing --> <serviceclass> com. Test. ws. ihelloservice </serviceclass> <! -- Full name of the Web Service Interface Class --> <implementationclass> com. Test. ws. helloserviceimpl </implementationclass> <! -- Full name of the web service implementation class --> <! -- When you do not need an interface, write the service in the serviceclass tag --> </service> </beans>

(7) Note: When Using list and other collection types, you need to define the mapping relationship.
It must be suffixed with. Aegis. XML with the same name as the interface.

<Mappings xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://xfire.codehaus.org/schemas/1.0/mapping.xsd"> <! -- Xfire supports basic types, but special configurations are required for Collection types --> <mapping> <method name = "gettestlist"> <! -- Method name to be configured --> <! -- Index = "0" indicates the serial number 0 of the method parameter, that is, the first parameter, the componenttype attribute indicates the type contained in the Set parameter --> <parameter index = "0" componenttype = "Java. lang. string "/> <! -- Configure the return type. The componenttype attribute indicates the class contained in the returned set --> <return-type componenttype = "com. test. WS. entervo "/> </method> </mapping> </mappings>


Both web. xml and service. XML can be automatically generated by IDE or handwritten.

(8) In this step, the WebService server is basically complete.
Deploy the project, start Tomcat, test the WSDL, and access http: // localhost: 8080/xfirewebservice/services/helloservice? WSDL

If the WSDL file is correctly displayed, the deployment is successful !!!

(9) create a web project (client) named xfirewebclient to call a WebService
Copy the xfire library file to the WEB-INF \ lib directory of the web project, at the same time you need to package the Service published on the server to the client, the Code published to the client only needs to be packaged with interface and parameter classes. The implementation classes do not need to be packaged into the client.

The jar package released here is named ihelloservice. jar, which contains three classes: ihelloservice, entervo, and exceedvo.

(10) create a servlet in this web project as the test servlet named clienttestservlet. Java
After configuring this servlet in Web. XML, you can write the WebService calling code in the servlet.

Package COM. test. WS; import Java. io. ioexception; import java.net. malformedurlexception; import Java. util. arraylist; import Java. util. list; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import Org. codehaus. xfire. xfire; import Org. codehaus. xfire. xfirefactory; import Org. codehaus. xfire. client. xfireproxyfactory; import Org. codehaus. xfire. service. service; import Org. codehaus. xfire. service. binding. objectservicefactory;/*** <p> title: clienttestservlet </P> * <p> description: test servlet </P> */public class clienttestservlet extends httpservlet {Private Static final long serialversionuid = 1l; Public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {request. setcharacterencoding ("UTF-8"); service servicemodel = new objectservicefactory (). create (ihelloservice. class); xfire = xfirefactory. newinstance (). getxfire (); xfireproxyfactory factory = new xfireproxyfactory (xfire); string serviceurl = "http: /localhost: 8080/xfirewebservice/services/helloservice"; ihelloservice client = NULL; try {client = (ihelloservice) factory. create (servicemodel, serviceurl);} catch (malformedurlexception e) {e. printstacktrace ();} string STR = client. getteststring ("Beijing"); Request. setattribute ("str", STR); entervo = new entervo (); entervo. setname ("yaodi"); entervo. setage (26); exceedvo = client. gettestobject (entervo); Request. setattribute ("VO", VO); List <string> Al = new arraylist <string> (); Al. add ("111"); Al. add ("222"); Al. add ("333"); List list = client. gettestlist (Al); Request. setattribute ("list", list); Request. getrequestdispatcher ("/result. JSP "). forward (request, response);} public void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {doget (request, response );}}

The Web. xml of the client is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet-Name> clienttestservlet </servlet-Name> <servlet-class> COM. test. WS. clienttestservlet </servlet-class> </servlet> <servlet-mapping> <servlet-Name> clienttestservlet </servlet-Name> <URL-pattern>/clienttest. DO </url-pattern> </servlet-mapping> <welcome-file-List> <welcome-File> clienttest. DO </welcome-File> </welcome-file-List> </Web-app>

(11) Note: The ihelloservice. Aegis. xml file in the xfirewebservice project should also be placed in the xfirewebclient project, at the same level as clienttestservlet. java.

(12) servlet return result page: result. jsp

<% @ Page Language = "Java" pageencoding = "UTF-8" %> <% @ taglib prefix = "C" uri = "http://java.sun.com/jsp/jstl/core" %> <% @ page iselignored = "false "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML> 

(13) Publish the WEB Project, start the xfirewebservice and xfirewebclient applications, and enter http: // localhost: 8080/xfirewebclient/in the address bar/

At this time, the client servlet will be called and Its doget method will be called. If it is normal, you can see the page output result (* ^__ ^ *)


Problem: When xfire is used to publish a service in a project, it is normal to test everything locally. However, when it is uploaded to the server, it is found that the first element of the List has no content, and the subsequent element content is displayed normally,

There is no problem through debugging the server, and it is lost during transmission to the client. Currently, solution 2 is to add a piece of junk data in front of the list, deliberately squeeze the first element of the list.
Hope someone can help me answer this question !!! Thank you.

The second is to use the SOAP protocol:Sometimes it is necessary to use other languages as the server, Java as the client, and soap to obtain WebService.

Soap Simple Object Access Protocol is a lightweight, simple, XML-based protocol designed to exchange structured and solidified information on the Web.

The example here demonstrates that both the server and client are Java

First download soapfrom the website http://xml.apache.org/soap/index.htmlto decompress soap.war.
Put soap. War in the Tomcat \ webapps \ directory.

(1) create a web project (server) named soapservice

(2) Compile the server code helloworldservice. Java

Package helloworld;/*** <p> title: helloworldservice </P> * <p> Description: server </P> */public class helloworldservice {Public String getmessage () {return "Hello world !!! ";} Public String getmessage (string str1, string str2) {return" Hello world! "+ Str1 +" & "+ str2 ;}}

After compiling, release the helloworldservice jar to the Tomcat \ Lib \ directory.

(3) Release of the soap Service
Start tomcat to automatically decompress soap. War and access http: // localhost: 8080/soap/admin/. The Management page of soap appears.
Note: An error occurs because Sun's mail. jar is missing in the Tomcat \ Lib \ directory.
Enter deploy and enter the following information:
ID: Hello
Scope: Request
Methods getmessage
Provider type: Java
Java provider class: helloworld. helloworldservice
Java provider static: No
Confirm release. You can click list to view published services!

(4) create another web project (client) named soapclient
Add four jar files to the project: xerces, soap, activation, and mail.

(5) create a servlet in this web project as the test servlet named helloworldclientservlet. Java
After configuring this servlet in Web. XML, you can write the WebService calling code in the servlet.

Package helloworld; import Java. io. ioexception; import java.net. URL; import Java. util. vector; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import Org. apache. soap. constants; import Org. apache. soap. fault; import Org. apache. soap. soapexception; import Org. apache. soap. RPC. call; import Org. apache. soap. RPC. parameter; import Org. apache. soap. RPC. response;/*** <p> title: helloworldclientservlet </P> * <p> description: test servlet </P> */public class helloworldclientservlet extends httpservlet {Private Static final long serialversionuid = 1l; Public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {request. setcharacterencoding ("UTF-8"); string endpoint = "http: // localhost: 8080/soap/servlet/rpcrouter"; // The URL is fixed, bind Call = new call () with parameters; // create an RPC callcall. settargetobjecturi ("hello"); // remote service name call. setmethodname ("getmessage"); // call the access method. setencodingstyleuri (constants. ns_uri_soap_enc); // sets the encoding style // releases the parameter-based service vector Params = new vector (); parameter p1 = new parameter ("name", String. class, "Guan Yu", null); parameter P2 = new parameter ("name2", String. class, "Zhang Fei", null); Params. addelement (P1); Params. addelement (P2); call. setparams (Params); Url url = new URL (endpoint); // the URL of the soap service, which starts to send RPC requests and returns the response resp = NULL from the server; try {// check whether there is a Chinese error in the Response Message (print the error message if there is a mistake, and print the returned information if there is a mistake) resp = call. invoke (URL, "");} catch (soapexception e) {e. printstacktrace ();} If (resp. generatedfault () {fault = resp. getfault (); system. out. println ("the following error occured:"); system. out. println ("fault code =" + fault. getfaultcode (); system. out. println ("fault string =" + fault. getfaultstring ();} else {parameter result = resp. getreturnvalue (); system. out. println (result. getvalue (); Request. setattribute ("str", result. getvalue ();} request. getrequestdispatcher ("/result. JSP "). forward (request, response);} public void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {doget (request, response );}}

The Web. xml of the client is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet-Name> helloworldclientservlet </servlet-Name> <servlet-class> helloworld. helloworldclientservlet </servlet-class> </servlet> <servlet-mapping> <servlet-Name> helloworldclientservlet </servlet-Name> <URL-pattern>/helloworldclientservlet. DO </url-pattern> </servlet-mapping> <welcome-file-List> <welcome-File> helloworldclientservlet. DO </welcome-File> </welcome-file-List> </Web-app>

(6) servlet return result page: result. jsp

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% @ taglib prefix =" C "uri =" http://java.sun.com/jsp/jstl/core "%> <% @ page iselignored =" false "%> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML> 

(7) run the client and test whether the client has passed
Start soapservice and soapclient at the same time and access http: // localhost: 8080/soapclient/
We should be able to see the returned content, which proves that the configuration and test are successful. Then we can release our own soap service!

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.