webservice是一种跨编程语言和操作系统的远程调用技术。通俗来讲即:将一些内部系统的业务方法发布成webservice服务,供其他使用者调用。具体相关原理可自行查询。本文是介绍在spring+maven框架的基础上,基于Java编程语言和Apache CXF框架来实现服务端业务方法发布成webservice的过程。
1.构建基本的maven项目mavenTest,并搭建基本的spring框架
本文搭建了springmvc+spring+mybatis架构,即添加相关依赖jar和配置文件,可实现对MySQL数据库的操作。
2.在pom.xml中添加Apache cxf框架的依赖jar包
3.在web.xml中配置cxf servlet<!-- cxf config --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.1.8</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.1.8</version> </dependency>
<servlet> <description>CXF Endpoint</description> <display-name>cxf</display-name> <servlet-name>cxf</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cxf</servlet-name> <url-pattern>/services/*</url-pattern><!-- 开放服务列表路径 --> </servlet-mapping>
4.在spring容器配置文件中添加
<import resource="spring-cxf.xml" /><!-- 导入cxf配置文件 -->
spring-cxf.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" 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"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <!-- Cxf WebService 服务端示例 --> <jaxws:endpoint id="demoWebservice" implementor="mavenTest.service.DemoWebserviceImpl" address="/demo"/> </beans>
5.经过以上的配置,接下来准备需要发布成webservice服务的业务方法,即上面配置文件中的id="demoWebservice"
package mavenTest.service; import javax.jws.WebService; @WebService public interface DemoWebservice { public String query(); public String queryById(String id); }
package mavenTest.service; import java.util.List; import javax.jws.WebService; import org.springframework.beans.factory.annotation.Autowired; import com.google.gson.Gson; import mavenTest.dao.StudentsMapper; @WebService(endpointInterface = "mavenTest.service.DemoWebservice") public class DemoWebserviceImpl implements DemoWebservice{ @Autowired private StudentsMapper dao; @Override public String query() { // TODO Auto-generated method stub List list=dao.selectAll(); return new Gson().toJson(list); } @Override public String queryById(String id) { // TODO Auto-generated method stub return new Gson().toJson(dao.selectByPrimaryKey(id)); } }
6.将mavenTest部署到Tomcat,在浏览器中输入http://localhost:8080/services/,如下图所示
7.上图为webservice列表,点击WSDL链接,即可查看文件