webservice和spring相结合
(一):首先先导入架包
<!-- spring并入webservice接口所需要的jar --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-ws-security</artifactId> <version>${cxf.version}</version> </dependency>
自己用的是<cxf.version>2.6.2</cxf.version>
(二)修改web.xml
<!-- 集成webservice接口 --> <servlet> <display-name>CXFServlet</display-name> <servlet-name>CXFServlet</servlet-name> <servlet-class> org.apache.cxf.transport.servlet.CXFServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- 过滤掉所有已webservice开头的链接,并且是webservice的链接 --> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/webservice/*</url-pattern> </servlet-mapping>
(三)在spring配置文件中配置接口并且进行发布
<!-- 部署webservice接口 --> <bean id="webServiceImpl" class="com.kaishengit.business.webservice.WebServiceImpl" /> <jaxws:endpoint id="webServiceImplEndpoint" implementor="#webServiceImpl" address="/test" />
注意的是在配置头上
<beans xmlns=" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
(四)接下来是贴代码时刻了
1 package com.kaishengit.business.webservice; 2 3 import javax.jws.WebMethod; 4 import javax.jws.WebService; 5 6 //使用@WebService注解标注WebServiceI接口 7 @WebService 8 public interface WebServiceI { 9 10 //使用@WebMethod注解标注WebServiceI接口中的方法 11 @WebMethod 12 String sayHello(String name); 13 14 @WebMethod 15 String save(String name,String pwd); 16 }
package com.kaishengit.business.webservice; import javax.jws.WebService; //使用@WebService注解标注WebServiceI接口的实现类WebServiceImpl @WebService public class WebServiceImpl implements WebServiceI { public String sayHello(String name) { System.out.println("WebService sayHello "+name); return "return:sayHello "+name; } public String save(String name, String pwd) { System.out.println("WebService save "+name+", "+pwd); return "save Success"; } }
当启动tomcat起来的时候我们输入:http://localhost:8080/myproject/webservice/test?wsdl 可以看到下图所示:
说明已经发布成功了!
(五)调用,还是使用自动生成代码;首先进入项目的文件;在cmd窗口中输入:执行命令:wsimport -keep url(url为wsdl文件的路径)生成客户端代码。
例如:wsimport -keep http://localhost:8080/myproject/webservice/test?wsdl
就可以自动生成代码了。
调用代码:
1 package com.kaishengit.business.webservice; 2 3 public class Mytest { 4 5 public static void main(String[] args) { 6 WebServiceImplService w = new WebServiceImplService(); 7 WebServiceI web = w.getWebServiceImplPort(); 8 9 System.out.println(web.sayHello("你妹")); 10 11 } 12 13 }
可以看到:
到这边调用成功!