1.SOAP协议
Simple Object Access Protocol即简单对象访问协议,是已汇总轻量级的、简单的、基于XML的协议,其目的就是用来在Web上交换结构化的信息。
2.定义介绍
webservice被用来提供服务,服务定义好之后,需要将其发布出去,客户端想要使用此服务,就需要查看其配置文档(WSDL),如果服务很多的时候需要一个管理平台将这些服务都管理起来,这个平台就叫UDDI。在使用该服务过程中,使用SOAP协议来进行发送请求和返回响应的过程就是基于SOAP的WebService服务,SOAP的消息必须有应用程序创建和处理。
3.SOAP消息格式
通常来讲SOAP消息的就恶狗格式包含以下元素:
- 信封(Envelope)--必须项
- 消息头(header)--必须项
- 主体(body)--必须项
- 附件(attachment)--选择项,可有可无
4.实例:下面进行一个简单的Webservice服务实例
(1)java本机运行:
编写服务端代码:
package com.self.webSoap;
import javax.jws.WebService;
@WebService
public class HelloSoap {
public String sayHello(String name){
return "hello," + name + " I'm soap";
}
}
启动服务端:
package com.self.webSoap;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class Test {
public static void main(String[] args) {
JaxWsServerFactoryBean jaxWsServerFactoryBean = new JaxWsServerFactoryBean();
jaxWsServerFactoryBean.setServiceClass(HelloSoap.class);
jaxWsServerFactoryBean.setServiceBean(new HelloSoap());
jaxWsServerFactoryBean.setAddress("http://localhost:9999/hello");
jaxWsServerFactoryBean.create();
}
}
访问:http://localhost:9999/hello?wsdl 查看Wsdl文件信息。
启动成功
启动成功后iu,根据发布的wsdl文件执行wsdl2java 指令生成客户端,然后进行调用。
(2)Tomcat启动
创建服务端:
增加代码:@BindingType(SOAPBinding.SOAP12HTTP_BINDING)
package com.self.webSoap;
import javax.jws.WebService;
import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding;
@WebService
@BindingType(SOAPBinding.SOAP12HTTP_BINDING)
public class HelloSoap {
public String sayHello(String name){
return "hello," + name + " I'm soap";
}
}
然后在web-inf下增添两个文件:
配置sun-jaxws.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
<!-- 服务路径http://网站路径/services/hello webserviceimpl-->
<endpoint name="hello" implementation="com.self.webSoap.HelloSoap" url-pattern="/sayhellosoap" />
</endpoints>
配置web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>WebserviceSoap</display-name>
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>sayhellosoap</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sayhellosoap</servlet-name>
<url-pattern>/sayhellosoap</url-pattern>
</servlet-mapping>
</web-app>
然后运行run onserver:
在url改为:http://localhost:8080/webServiceSoap/sayhellosoap,看到以下界面,发布成功:
tomcat项目见: