The server is a web project and the client is a Java project. Check the server code first.
The first is sei, that is, helloservice. Java, the server interface class.
package com.jadyer.service;import javax.jws.WebParam;import javax.jws.WebResult;import javax.jws.WebService;@WebService(targetNamespace="http://blog.csdn.net/jadyer")public interface HelloService {@WebResult(name="sayHelloResult")public String sayHello(@WebParam(name="name")String name);}
The following is SIB, that is, helloserviceimpl. Java, the server interface implementation class.
Package COM. jadyer. service; import javax. annotation. resource; import javax. JWS. webService; import javax. servlet. HTTP. httpservletrequest; import javax. XML. WS. webservicecontext; import javax. XML. WS. handler. messagecontext; import javax. XML. WS. handler. soap. soapmessagecontext; import Org. springframework. stereotype. service; import COM. jadyer. dao. hellodaojdbc;/*** get httpservletapi when integrating the JAX-WS with spring * 1) SIB directly use @ resource injection javax. XML. WS. webservicecontext * 2) use WSC. getmessagecontext (). get (soapmessagecontext. servlet_request) Get httpservletrequest *, provided that SIB has been managed by spring .. the obvious feature in this example is that SIB uses the @ service annotation * @ create may 27,201 3 6:10:50 pm * @ author Xuan Yu
The following is a DAO implementation class hellodaojdbc. Java simulated by the server.
package com.jadyer.dao;import org.springframework.stereotype.Repository;@Repository("helloDao")public class HelloDaoJDBC {public String sayHello(String name) {System.out.println("Receive the name=[" + name + "]");if(null==name){return "Hello,World";}else{return "Hello," + name;}}}
The following is the handler class licensehandler. Java customized by the server.
Package COM. jadyer. handler; import Java. util. iterator; import Java. util. set; import javax. servlet. HTTP. httpservletrequest; import javax. XML. namespace. QNAME; import javax. XML. soap. soapbody; import javax. XML. soap. soapenvelope; import javax. XML. soap. soapexception; import javax. XML. soap. soapheader; import javax. XML. soap. soapheaderelement; import javax. XML. soap. soapmessage; import javax. XML. WS. handler. messageconte XT; import javax. XML. WS. handler. soap. soaphandler; import javax. XML. WS. handler. soap. soapmessagecontext; public class licensehandler implements soaphandler <soapmessagecontext >{@ overridepublic set <QNAME> getheaders () {return NULL ;}@ overridepublic void close (messagecontext context) {}@ overridepublic Boolean handlefault (soapmessagecontext context) {system. out. println ("server. handlefault () is invoked ...... "); Return false ;}@ override @ suppresswarnings (" unchecked ") Public Boolean handlemessage (soapmessagecontext context) {system. out. println ("server. handlemessage () is invoked ...... "); // The httpservletrequest obtained here is not nullhttpservletrequest request = (httpservletrequest) context only after handler is incorporated into spring management. get (soapmessagecontext. servlet_request); system. out. println ("realpath =" + request. getsession (). getservletcontext (). Getrealpath ("/"); // from the server perspective: Inbound indicates receiving the client message, and outbound indicates responding to the message to the client .. from the client perspective, it is exactly the opposite: Boolean isoutbound = (Boolean) context. get (messagecontext. message_outbound_property); If (isoutbound) {return true;} soapmessage message = context. getmessage (); soapheader header = NULL; soapbody body = NULL; try {soapenvelope envelope = message. getsoappart (). getenvelope (); header = envelope. getheader (); Body = envelope. getbod Y ();} catch (soapexception e) {e. printstacktrace ();} // obtain part namestring partname = body in the body. getchildnodes (). item (0 ). getlocalname (); // only verifies the login () method opened on the server. Otherwise, it verifies all the methods opened on the server if (! "Sayhello ". equals (partname) {return true;} If (null = header) {system. out. println ("No header information found ...... "); Return true;} iterator <soapheaderelement> iterator = header. extractallheaderelements (); If (! Iterator. hasnext () {system. out. println ("header information cannot be blank ...... "); Return true;} system. out. println ("protocol valid ...... "); While (iterator. hasnext () {system. out. println (iterator. next (). gettextcontent ();} return true ;}}
The following is the spring configuration file applicationcontext. xml.
<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: Core = "http://jax-ws.dev.java.net/spring/core" xmlns: servlet = "http://jax-ws.dev.java.net/spring/servlet" xsi: schemalocation = "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2. 5. xsdhttp: // your http://jax-ws.dev.java.net/spring/servlet.xsd "> <context: component-scan base-package =" com. jadyer "/> <! -- JAX-WS and spring Integration --> <! -- There are two better methods: simplejaxwsserviceexporter provided by spring and wsspringservlet provided by jaxws-spring --> <! -- The difference between the two methods is that the configuration files are different, while the SEI and SIB are the same --> <! -- Supplement: the reason for the integration of JAX-WS and spring is mainly to let SIB into spring management, so that we can inject things to SIB, such as Dao and so on --> <! --*************************************** **************************************** ******************** --> <! -- The following describes how to write simplejaxwsserviceexporter provided by spring --> <! --*************************************** **************************************** ******************** --> <! -- Simplejaxwsserviceexporter automatically searches for Classes containing javax. JWS. WebService annotations in the package, and publishes them as WebService --> <! -- This method can directly inject objects into SIB, because this WebService has been managed by spring. For details, see helloserviceimpl. Java in this example. --> <! -- Value indicates the publishing address. It must not be the same as the Web application address. The address used for access is 'value' and @ WebService (servicename = '') --> <! -- Value = "http: // 127.0.0.1: 8088/mytest", the service address is http: // 127.0.0.1: 8088/mytestmyhelloservice? WSDL --> <! -- Value = "http: // 127.0.0.1: 8088/mytest", the service address is http: // 127.0.0.1: 8088/mytest/myhelloservice? WSDL --> <! -- The WebService published by this integration method is an independent WebService --> <! -- <Bean class = "org. springframework. remoting. jaxws. simplejaxwsserviceexporter "> <property name =" baseaddress "value =" http: // 127.0.0.1: 8088/mytest/"/> </bean> --> <! --*************************************** **************************************** ******************** --> <! -- The following shows how to write wsspringservlet provided by jaxws-spring --> <! --*************************************** **************************************** ******************** --> <! -- Jaxws-spring wsspringservlet development steps are as follows 1) Import jaxws-spring-1.8.jar, xbean-spring-3.13.jar, jaxws-ri-2.2.7 toolkit, three http://repo1.maven.org/maven2/org/jvnet/jax-ws-commons/spring/jaxws-spring/1.8/http://repo1.maven.org/maven2/org/apache/xbean/xbean-spring/3.13/https://jax-ws.java.net (I downloaded the latest version of jaxws2.2.7-20120813.zip) 2) add two XSD of jaxws-spring in the spring configuration file. Note that the XSD is added at http://jax-ws.dev.java.net/spring/core.xsd, and core.xsdis not. Is the spring-jax-ws-core.xsd, otherwise it will report an error 3) add two schemas of jaxws-spring for the XML file in myeclipse for ease in applicationcontext. in XML, compile the jaxws-spring label window-preferences-myeclipse enterprise workbench-files and editors-XML-XML catalog-user specified entries location: select File System and then select the spring-jax-ws-core.xsd file on the local hard disk (which can be extracted directly from the jaxws-spring-1.8.jar) Key type: Select System ID key: Enter http://jax-ws.dev.java.net/spring/core.xsd4) Write wsspringservlet In applicationcontext. XML, configure 5) Compile web. xml --> <! -- Here, the URL value must be the same as the <URL-pattern> value configured for wsspringservlet in Web. xml --> <! -- After the web application is started, the published service access address is http: // 127.0.0.1: 8088/webpath/myservice? WSDL --> <servlet: Binding url = "/myservice"> <servlet: Service> <! -- The bean attribute indicates the injection object of WebService. Note that the value must be added with a well number at the beginning, followed by the bean name of SIB managed by spring --> <core: service bean = "# helloserviceimpl"> <! -- In this case, @ handlerchain (file = "myhandlerchain. XML "), and you do not need to write myhandlerchain. XML --> <core: handlers> <Bean class = "com. jadyer. handler. licensehandler "/> </core: handlers> <! -- Proactively declare the external file of the WSDL File Import or include, otherwise the XSD will not be correctly introduced in the published WSDL --> <! -- <Core: Metadata> <value>/WEB-INF/WSDL/myhello. XSD </value> </core: Metadata> --> </core: Service> </servlet: Binding> </beans>
The following figure shows log4j. properties for log printing.
# Running hh: mm: SS}] [% T] [% c {1}] % m % N
Finally, the Web. xml of the server
<? 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"> <context-param> <param-Name> contextconfiglocation </param-Name> <param-value> classpath: applicationcontext. XML </param-value> </context-param> <listener-class> Org. springframewo Rk. Web. Context. contextloaderlistener </listener-class> </listener> <! -- Configure jaxws-spring --> <servlet-Name> jaxws-servlet </servlet-Name> <servlet-class> COM. sun. XML. WS. transport. HTTP. servlet. wsspringservlet </servlet-class> </servlet> <servlet-mapping> <servlet-Name> jaxws-servlet </servlet-Name> <URL-pattern>/myservice </URL -Pattern> </servlet-mapping> </Web-app>
Now, the server code example is complete. The following is the client code
First, the headerhandler. Java customized by the client
package com.jadyer.handler;import java.io.IOException;import java.util.Set;import javax.xml.namespace.QName;import javax.xml.soap.SOAPEnvelope;import javax.xml.soap.SOAPException;import javax.xml.soap.SOAPHeader;import javax.xml.soap.SOAPMessage;import javax.xml.ws.handler.MessageContext;import javax.xml.ws.handler.soap.SOAPHandler;import javax.xml.ws.handler.soap.SOAPMessageContext;public class HeaderHandler implements SOAPHandler<SOAPMessageContext> {@Overridepublic Set<QName> getHeaders() {return null;}@Overridepublic void close(MessageContext context) {}@Overridepublic boolean handleFault(SOAPMessageContext context) {System.out.println("\nClient.handleFault() is invoked.....");return false;}@Overridepublic boolean handleMessage(SOAPMessageContext context) {System.out.println("\nClient.handleMessage() is invoked.....");Boolean isOutBound = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);if(isOutBound){SOAPMessage message = context.getMessage();try {SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();SOAPHeader header = envelope.getHeader();String partName = envelope.getBody().getFirstChild().getLocalName();if("sayHello".equals(partName)){if(null == header){header = envelope.addHeader();}QName qname = new QName("http://blog.csdn.net/jadyer", "licenseInfo", "ns");header.addHeaderElement(qname).setValue("Jadyer");message.writeTo(System.out);}} catch (SOAPException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}return true;}}
Next is the handlerresolver class used for integration between the client and spring.
package com.jadyer.handler;import java.util.ArrayList;import java.util.List;import javax.xml.ws.handler.Handler;import javax.xml.ws.handler.HandlerResolver;import javax.xml.ws.handler.PortInfo;import org.springframework.stereotype.Component;@Componentpublic class HeaderHandlerResolver implements HandlerResolver {@SuppressWarnings("unchecked")@Overridepublic List<Handler> getHandlerChain(PortInfo portInfo) {List<Handler> handlers = new ArrayList<Handler>();handlers.add(new HeaderHandler());return handlers;}}
The following is a service implementation class clientservice. Java simulated by the client.
package com.jadyer.service;import javax.annotation.Resource;import net.csdn.blog.jadyer.HelloService;import org.springframework.stereotype.Service;@Servicepublic class ClientService {@Resourceprivate HelloService myServerWebService;public String getServerResponse(String name){return myServerWebService.sayHello(name);}}
The following is the spring configuration file applicationcontext. xml of the client.
<? XML version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemalocation = "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-con Text-2.5.xsd "> <context: component-scan base-package =" com. jadyer "/> <! -- In this way, you can inject a WebService to other beans on the client --> <bean id = "myserverwebservice" class = "org. springframework. remoting. jaxws. jaxwsportproxyfactorybean "> <! -- Remember to use wsimport to generate the client code first, and then write the full path of the Interface Class in the value of serviceinterface --> <! -- About the use of wsimport, can refer to my blog http://blog.csdn.net/jadyer/article/details/8692108 --> <! -- Wsimport-d:/download/-keep-verbose http: // 127.0.0.1: 8088/jaxws-spring/myservice? WSDL --> <property name = "serviceinterface" value = "net. csdn. blog. jadyer. helloservice "/> <property name =" wsdldocumenturl "value =" http: // 127.0.0.1: 8088/jaxws-spring/myservice? WSDL "/> <property name =" namespaceuri "value =" http://blog.csdn.net/jadyer "/> <property name =" servicename "value =" myhelloservice "/> <property name =" portname "Value = "helloserviceimplport"/> <! -- Use the handlerresolver attribute to enable handler. However, the value of this attribute must be of the javax. xml. ws. handler. handlerresolver type. --> <! -- Therefore, you need to customize a class to implement the handlerresolver interface. For details, refer to com. jadyer. handler. headerhandlerresolver. java --> <property name = "handlerresolver" ref = "headerhandlerresolver"/> </bean> </beans>
Finally, the client calls the simulation entry clientapp. Java of the server.
Note: The specific client WebService code is generated by wsimport, see http://blog.csdn.net/jadyer/article/details/8692108
Package COM. jadyer. client; import Org. springframework. context. applicationcontext; import Org. springframework. context. support. classpathxmlapplicationcontext; import COM. jadyer. service. clientservice; public class clientapp {public static void main (string [] ARGs) {applicationcontext CTX = new classpathxmlapplicationcontext ("applicationcontext. XML "); clientservice cs = (clientservice) CTX. getbean ("clientservice"); system. out. println (CS. getserverresponse (" "));}}
The console output is also listed below
// Client. handlemessage () is invoked ..... <s: envelope xmlns: S = "http://schemas.xmlsoap.org/soap/envelope/"> <s: Header> <ns: licenseinfo xmlns: NS = "http://blog.csdn.net/jadyer"> jadyer </ns: licenseinfo> </s: header> <s: Body> <ns2-sayhello xmlns: ns2-= "http://blog.csdn.net/jadyer"> <Name> Xuan Yu </Name> </ns2-sayhello> </s: body> </S: envelope> client. handlemessage () is invoked ..... hello, Xuan Yu // server. handlemessage () is invoked ...... realpath = D: \ develop \ apache-Tomcat-6.0.36 \ webapps \ jaxws-spring \ protocol valid ...... jadyer ------------------------------------------------------------------------ servletcontextname = nullcontextpath =/jaxws-springrealpath = D: \ develop \ apache-Tomcat-6.0.36 \ webapps \ jaxws-spring \ serverinfo = Apache Tomcat/6.0.36 export receive the name = [Xuan Yu] server. handlemessage () is invoked ...... realpath = D: \ develop \ apache-Tomcat-6.0.36 \ webapps \ jaxws-spring \