在上两篇文章中我们讲了Webservice的服务提供端和服务调用端,但是接下来怎么在项目中使用呢?学以致用才是我们学习的最终目的。学习前提:大家在学习这篇文章时需要有Spring框架和Maven构建工具的使用经验(项目中Spring的配置、Maven工具的使用不再讲述)。
环境准备:
Windows7
JDK7
Eclipse4.4.2
Maven
Spring4
在Eclipse中创建一个Maven项目,项目名称为:oaproj
1、在pom.xml中引入WebService相关的jar依赖
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxws -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.6</version>
</dependency>
2、在web.xml加载启动Webservice
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
3、创建WebService相关的Spring配置文件:spring-webservie.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:jaxws="http://cxf.apache.org/jaxws"
xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd">
<bean id="userServiceImpl" class="cn.com.webservice.user.UserServiceImpl" />
<jaxws:endpoint id="userServiceImplService" address="/user"
implementor="#userServiceImpl">
</jaxws:endpoint>
</beans>
4、把服务端代码迁移到项目的\src\main\java\cn\com\webservice\user,如下图:
注释:
(1)迁入到框架中后\src\main\java\cn\com\webservice\user路径下的类StartServer.java已经没用可以删除,服务的创建及启动在第3步中进行
(2)把\src\main\java\cn\com\webservice\user\UserServiceImpl.java类的endpointInterface="cn.com.UserService"修改为endpointInterface="cn.com.webservice.user.UserService"
5、启动oaproj项目,并在浏览器中访问地址:http://127.0.0.1:8080/oaproj/services/user?wsdl,成功则如下图: