[HELLO WORLD] 用CXF创建Web Service

SERVER

1.新建一个maven web 工程,加入cxf依赖

<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>


2.新建服务接口以及实现类

@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());
	}

}


3.发布的servlet

@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了。


CLIENT

1.新建一个maven工程。在pom中添加cxf-codegen-plugin插件

<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>


2.生成stub

run as Maven generate-sources,会在工程目录,也就是${project.build.sourceDirectory}中,根据发布的wsdl生成对应的stub.

3.client类

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());
	}

}



helloworld 完成




你可能感兴趣的:(maven,CXF)