<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>
@WebService public interface School { Student add(Kid kid); }
@WebService(endpointInterface="cn.lwy.ws.school.School") public class SchoolImpl implements School{ AtomicInteger ai = new AtomicInteger(1000); @Override public Student add(Kid kid) { int code = ai.getAndIncrement(); System.out.println("add kid "+kid.getName() +" with code "+code); return new Student(code,kid.getName()); } }
@WebServlet(urlPatterns = "/ws/*") public class MyCXFServlet extends CXFNonSpringServlet { private static final long serialVersionUID = 1L; @Override public void loadBus(ServletConfig servletConfig) { super.loadBus(servletConfig); Bus bus = getBus(); BusFactory.setDefaultBus(bus); Endpoint.publish("/add", new SchoolImpl()); } }
这里访问用浏览器访问http://ip:port/contexroot/ws 控制台会抛出一个异常
java.lang.IllegalStateException: getWriter() has already been called for this response是在请求
<LINK type="text/css" rel="stylesheet" href="/jaxws/ws/?stylesheet=1">的时候抛出的,或许是cxf的一个bug,不过不影响wsdl的发布,就先不去管他了。
访问http://ip:port/contexroot/ws/add?wsdl,应该可以看到发布好的wsdl了。
<plugin> <groupId>org.apache.cxf</groupId> <artifactId>cxf-codegen-plugin</artifactId> <version>${cxf.version}</version> <executions> <execution> <id>generate-sources</id> <phase>generate-sources</phase> <configuration> <sourceRoot>${project.build.sourceDirectory}</sourceRoot> <wsdlOptions> <wsdlOption> <wsdl>http://ip:port/contextroot/ws/add?wsdl</wsdl> </wsdlOption> </wsdlOptions> </configuration> <goals> <goal>wsdl2java</goal> </goals> </execution> </executions> </plugin>
run as Maven generate-sources,会在工程目录,也就是${project.build.sourceDirectory}中,根据发布的wsdl生成对应的stub.
public class MyCXFClient { public static void main(String[] args) { SchoolImplService service = new SchoolImplService(); School school = service.getSchoolImplPort(); Kid kid = new Kid(); kid.setName("Tom"); Student student = school.add(kid); System.out.println(student.getName() + " : " + student.getCode()); } }