1.导入jar包(没有筛除多余的jar包)
2.配置web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
配置beans.xml
位置:WEB-INF/beans.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-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint
id="zhshch"
implementor="com.zhshch.test.Hello"
address="/abc" />
</beans>
解释:
<jaxws:endpoint
id="zhshch" //随便写
implementor="com.zhshch.test.Hello" //资源接口实现类
address="/abc" /> //随便写,url访问路径
如url:http://localhost:8080/MyCxf/services/abc
3.接口和实现类
接口:
@WebService
public interface IHello {
public String sayHello(String name);
public List<String> sayList(List<String> list) ;
public Student sayStu(Student stu) ;
}
实现类:
@WebService
public class Hello implements IHello {
public String sayHello(String name) {
return "hello ," + name ;
}
public List<String> sayList(List<String> list) {
return list ;
}
public Student sayStu(Student stu) {
return stu ;
}
}
pojo(测试自定义对象使用):
public class Student {
public Student(){}
public Student(String name ,int age){
this.name = name;
this.age = age ;
}
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
完成上述步骤,运行web工程
浏览器输入http://localhost:8080/MyCxf/services
结果如下:
4.客户端调用
public static void test1() throws Exception{
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(IHello.class); //用接口类IHello,不用Hello
factory.setAddress("http://localhost:8080/MyCxf/services/abc");
IHello client = (IHello) factory.create(); //接口类
//字符串
String reply = client.sayHello("周星驰") ;
System.out.println("Server said: " + reply);
//list
List<String> list = client.sayList(Arrays.asList(new String[]{"abc","efg"})) ;
System.out.println(list);
//pojo
Student stu = client.sayStu(new Student("batman",20)) ;
System.out.println(stu.getName() + "," + stu.getAge());
}
demo