1、用eclipse新建web工程。
2、解压下载的CXF,把lib下面所有包copy到该工程lib下。
3、写接口
package server;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService
public interface iHelloWorld {
//加入WebParam注解,以保证xml文件中参数名字的正确性
String sayHi(@WebParam(name="text") String text);
}
4、实现类
package server;
import javax.jws.WebService;
@WebService(endpointInterface = "server.iHelloWorld", serviceName = "hi")
public class HelloWorldImpl implements iHelloWorld {
public String sayHi(String text) {
System.out.println("sayHi called");
return "Hello " + text;
}
}
5、注册或者叫加入容器(类似spring)
import javax.servlet.ServletConfig;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.transport.servlet.CXFNonSpringServlet;
import server.HelloWorldImpl;
import server.iHelloWorld;
public class WebServelet extends CXFNonSpringServlet { //主要是这一个继承CXFNonSpringServlet
private static final long serialVersionUID = 1L;
@Override
protected void loadBus(ServletConfig sc) {
super.loadBus(sc);
Bus b=getBus();
BusFactory.setDefaultBus(b);
HelloWorldImpl hi=new HelloWorldImpl();//实现类
ServerFactoryBean sfb=new ServerFactoryBean(); //server工厂
sfb.setServiceClass(iHelloWorld.class);// 接口类
sfb.setAddress("/hi"); //服务请求路径
sfb.setServiceBean(hi);
sfb.create();
}
}
6、配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>cxfServlet</servlet-name> <servlet-class>WebServelet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cxfServlet</servlet-name> <url-pattern>/ws/*</url-pattern> </servlet-mapping> </web-app>