java maven cxf笔记
Posted 土豆你个马铃薯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java maven cxf笔记相关的知识,希望对你有一定的参考价值。
IDE:
一:新建Maven项目
1.File->New->Project..
2.
3.
4.
二:添加cxf和jetty依赖
<dependencies> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-frontend-jaxws --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.cxf/cxf-rt-transports-http-jetty --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>3.0.1</version> </dependency> </dependencies>
三:添加webService服务端
1.service接口定义:
@WebService public interface service { String sayHello(String param); }
2.接口实现类
@WebService public class serviceimpl implements service { public String sayHello(String param) { System.out.println(param+"正在调用sayHello()方法..."); return "Hello->"+param; } }
3.服务提供
import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; /** * Description:webservice启动 * 启动后webservice对外暴露地址为:http://localhost:8080/service?wsdl * Created by Admin on 2017/7/26. */ public class server { public static void main(String[] args) { JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean(); factory.setServiceClass(serviceimpl.class); factory.setAddress("http://localhost:8080/service"); Server server = factory.create(); server.start(); } }
四:启动服务端
1.启动server中的main方法
2.浏览器访问http://localhost:8080/service?wsdl
webservice服务启动成功!
五:添加Client客户端(客户端调用服务的两种方式)
1.静态调用
import com.cxf.service.service; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; /** * Description:静态调用需要依赖service类, * 因为客户端调用cxf,webservice接口的过程中需要服务器端提供service, * 很不方便,如果同一个项目中则没有区别。 * Created by Admin on 2017/7/26. */ public class client { public static void main(String[] args) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setAddress("http://localhost:8080/service"); factory.setServiceClass(service.class); service service = (service) factory.create(); System.out.println(service.sayHello("cxf")); }
2.动态调用
import org.apache.cxf.endpoint.Client; import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; import javax.xml.namespace.QName; public class client { /**动态调用完全不依赖service类, * 服务器端只要提供接口名和路径就可以方便的调用 */ public static void main(String[] args) { JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); /**url为调用webService的wsdl地址*/ Client client = dcf.createClient("http://localhost:8080/service?wsdl"); /**namespace是命名空间(wsdl文件中的targetNamespace属性),localPart是需要调用的方法名*/ QName name = new QName("http://service.cxf.com/", "sayHello"); /**方法需要的参数*/ String xmlStr = "cxf"; Object[] objects; try { /**调用方法并获得返回值*/ objects = client.invoke(name, xmlStr); System.out.println(objects[0].toString()); } catch (Exception e) { e.printStackTrace(); } }
3.执行Client中对应的main函数即可
以上是关于java maven cxf笔记的主要内容,如果未能解决你的问题,请参考以下文章
在maven中,CXF自动生成失败并显示“Duplicated option:frontend”?