需要导入cxf需要的jar文件
首先需要有一个接口:
import java.util.List;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService
public interface HelloWord {
String sayHi(@WebParam(name="text")String text);
}
实现类:
import java.util.HashMap;
import javax.jws.WebService;
@WebService(endpointInterface="com.sg.service.HelloWord",serviceName="HelloWord")
public class HelloWordImpl implements HelloWord{
Map<Integer,User> userMap = new HashMap<Integer, User>();
@Override
public String sayHi(String text) {
return "hello-->"+text;
}
}
服务端发布程序:
package com.sg.service;
import javax.xml.ws.Endpoint;
import org.apache.cxf.configuration.spring.JAXBBeanFactory;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.apache.cxf.endpoint.Server;
public class HolleWordAPP {
public static void main(String[] args) {
System.out.println("web service start..............");
HelloWordImpl helloWordImpl = new HelloWordImpl();
String address = "http://localhost:8080/helloword";
Endpoint.publish(address, helloWordImpl);
System.out.println("web service end................");
//第二种发布服务方式
/*
JaxWsServerFactoryBean jsfb = new JaxWsServerFactoryBean();
//设置服务在服务器上部署的位置
jsfb.setAddress("http://localhost:8080/helloword");
//设置服务暴露的接口实现类
jsfb.setServiceClass(helloWordImpl.getClass());
Service service = (Service)jsfb.create();
service.start();
*/
}
}
发布之后可以直接访问http://localhost:8080/helloword?wsdl
会把相应的xml文件显示出来
下面是客户端程序:
package com.sg.client;
import java.util.ArrayList;
import java.util.List;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.sg.service.HelloWord;
import com.sg.service.User;
public class HelloWorldClient {
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
JaxWsProxyFactoryBean jpfb = new JaxWsProxyFactoryBean();
jpfb.getInInterceptors().add(new LoggingInInterceptor());
jpfb.getOutInterceptors().add(new LoggingOutInterceptor());
jpfb.setServiceClass(HelloWord.class);
jpfb.setAddress("http://localhost:8080/helloword");
HelloWord hw = (HelloWord)jpfb.create();
User u = new User();
u.setName("zhangsan");
u.setDescription("test");
users.add(u);
System.out.println(hw.sayHi("sungang"));
System.out.println(hw.sayHiToUser(u));
}
}