web service 之 cxf

例子1:

仅使用javax包下的类完成webservice

1.服务端代码,新建实体类com.hanjun.service.User

 private String name;
 public User(String name) {
  super();
  this.name = name;
 }
 public User() {
  super();
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }

新建接口类com.hanjun.service.HelloWorld

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {

    String sayHi(String text);
   
    User sayHiToUser(User user);

    User[] getUsers();
   
    Users getUserMap();
}

新建接口实现类com.hanjun.service.HelloWorldImpl

@WebService(endpointInterface = "com.hanjun.service.HelloWorld", serviceName = "HelloWorld")
public class HelloWorldImpl implements HelloWorld {
 
 HashMap<Integer, User> users = new HashMap<Integer, User>();

    public String sayHi(String text) {
        System.out.println("sayHi called");
        return "Hello " + text;
    }

    public User sayHiToUser(User user) {
        System.out.println("sayHiToUser called");
        users.put(users.size(), user);
        return user;
    }

    public Users getUserMap() {
        System.out.println("getUsers called");
        Users users = new Users();
        users.setMap(this.users);
        return users;
    }
 
 public User[] getUsers() {
  User[] us = new User[users.size()];
  for(Entry<Integer,User> entry : users.entrySet()){
   us[entry.getKey()] = entry.getValue();
  }
  return us;
 }
}

说明:Map和List没有经过特殊处理而直接返回时客户端收到的将是空值,此例中将Map封装到Users类来解决此问题,Users类中只有HashMap<Integer,User> map属性及get\set方法,属性类型要用Map或List的实现类,不能用接口类。

服务端发布:

    System.out.println("Starting Server");
    HelloWorldImpl implementor = new HelloWorldImpl();
    String address = "http://localhost:9000/helloWorld";
    Endpoint.publish(address, implementor);

说明:发布成功后在浏览器中输入http://localhost:9000/helloWorld?wsdl 能正常显示xml则表示发布成功。

2.客户端代码,客户端可通过cxf/bin中的wadl2java工具生成代码,也可以通过MyEclipse新建Web Service Client生成代码。

  URL url = null;
  try {
      URL baseUrl;
      baseUrl = HelloWorld.class.getResource(".");
      url = new URL(baseUrl, "http://localhost:9000/helloWorld?wsdl");
  } catch (MalformedURLException e) {
      e.printStackTrace();
  }
  Service service = Service.create(url,new QName("http://service.hanjun.com/","HelloWorld"));
  HelloWorld helloWorld = service.getPort(new QName("http://service.hanjun.com/","HelloWorldImplPort"), HelloWorld.class);
  String aa = helloWorld.sayHi("aa");
  System.out.println(aa);
  
  User user = new User("bb");
  User bb = helloWorld.sayHiToUser(user);
  System.out.println(bb.getName());
  
  HashMap<Integer,User> map = helloWorld.getUserMap().getMap();
  for(Entry<Integer,User> entry : map.entrySet()){
      System.out.println("map:"+entry.getValue().getName());
  }
  
  User[] us = helloWorld.getUsers();
  for(User u : us){
      System.out.println("[]:"+u.getName());
  }

例子2:

使用cxf的类来完成web service,支持直接传递List或Map.引入jar包

asm-3.3.1.jar
cxf-core-3.0.0-milestone2.jar
cxf-rt-bindings-soap-3.0.0-milestone2.jar
cxf-rt-databinding-jaxb-3.0.0-milestone2.jar
cxf-rt-frontend-jaxws-3.0.0-milestone2.jar
cxf-rt-frontend-simple-3.0.0-milestone2.jar
cxf-rt-transports-http-3.0.0-milestone2.jar
cxf-rt-transports-http-jetty-3.0.0-milestone2.jar
cxf-rt-transports-http-netty-server-3.0.0-milestone2.jar
cxf-rt-ws-addr-3.0.0-milestone2.jar
cxf-rt-ws-mex-3.0.0-milestone2.jar
cxf-rt-ws-policy-3.0.0-milestone2.jar
cxf-rt-ws-rm-3.0.0-milestone2.jar
cxf-rt-wsdl-3.0.0-milestone2.jar
geronimo-servlet_3.0_spec-1.0.jar
jaxb-core-2.2.7.jar
jaxb-impl-2.2.7.jar
jetty-continuation-8.1.14.v20131031.jar
jetty-http-8.1.14.v20131031.jar
jetty-io-8.1.14.v20131031.jar
jetty-server-8.1.14.v20131031.jar
jetty-util-8.1.14.v20131031.jar
neethi-3.0.3.jar
netty-buffer-4.0.7.Final.jar
netty-codec-4.0.7.Final.jar
netty-codec-http-4.0.7.Final.jar
netty-common-4.0.7.Final.jar
netty-handler-4.0.7.Final.jar
netty-transport-4.0.7.Final.jar
stax2-api-3.1.1.jar
woodstox-core-asl-4.2.0.jar
wsdl4j-1.6.3.jar
xmlschema-core-2.1.0.jar

1.服务端代码,使用1中的User类,接口类如下

@WebService
public interface HelloWorld {

    String sayHi(String text);

    User sayHiToUser(User user);

    User[] getUsers();
   
    Map<Integer,User> getUserMap();
   
    List<User> getUserList();
}

接口实现类:

public class HelloWorldImpl implements HelloWorld {
 
 Map<Integer, User> users = new HashMap<Integer, User>();

    public String sayHi(String text) {
        System.out.println("sayHi called");
        return "Hello " + text;
    }

    public User sayHiToUser(User user) {
        System.out.println("sayHiToUser called");
        users.put(users.size(), user);
        return user;
    }

    public Map<Integer,User> getUserMap() {
        System.out.println("getUsers called");
        return users;
    }

 public List<User> getUserList() {
     List<User> list = new ArrayList<User>();
         for(Entry<Integer,User> entry : users.entrySet()){
         list.add(entry.getValue());
     }
     return list;
 }
 
 public User[] getUsers() {
     User[] us = new User[users.size()];
     for(Entry<Integer,User> entry : users.entrySet()){
         us[entry.getKey()] = entry.getValue();
     }
     return us;
 }
}

服务端发布:

    public static void main(String args[]) throws Exception {
        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
        factory.setServiceClass(HelloWorldImpl.class);
        factory.setAddress("http://localhost:9000/helloWorld");
        
        // 添加客户端请求拦截器,打印请求参数
        factory.getInInterceptors().add(new LoggingInInterceptor());
        // 添加输出拦截器,打印输出内容
        factory.getOutInterceptors().add(new LoggingOutInterceptor());
       
        org.apache.cxf.endpoint.Server server = factory.create();
        System.out.println("Starting Server");
        server.start();
    }

2.客户端代码:

  JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
  factory.setAddress("http://localhost:9000/helloWorld");
  factory.setServiceClass(HelloWorld.class);
  HelloWorld helloWorld = (HelloWorld) factory.create();
  String aa = helloWorld.sayHi("aa");
  System.out.println(aa);
  ...

3.上面是使用的JAX-WS发布服务端和搭建客户端,CXF还可以使用POJO方式发布服务端和搭建客户端:

  ServerFactoryBean factory = new ServerFactoryBean();
  factory.setAddress("http://localhost:9000/helloWorld");
  factory.setServiceClass(HelloWorld.class);
  factory.setServiceBean(new HelloWorldImpl());
  factory.create();

  ClientProxyFactoryBean client = new ClientProxyFactoryBean();
  client.setServiceClass(HelloWorld.class);
  client.setAddress("http://localhost:9000/helloWorld");
  HelloWorld helloWorld = (HelloWorld) client.create();

CXF与spring整合

1.引入jar包

spring-aop-3.2.6.RELEASE.jar
spring-beans-3.2.6.RELEASE.jar
spring-context-3.2.6.RELEASE.jar
spring-core-3.2.6.RELEASE.jar
spring-expression-3.2.6.RELEASE.jar

2.src下新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jaxws="http://cxf.apache.org/jaxws"
 xsi:schemaLocation="Index of /schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://cxf.apache.org/jaxws
           http://cxf.apache.org/schemas/jaxws.xsd">
          
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
<!--    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>-->
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
   
<!--    <jaxws:endpoint id="helloWorld" -->
<!--     implementor="com.hanjun.service.HelloWorldImpl"-->
<!--     address="/HelloWorld"/>-->

 <jaxws:server id="helloWorld" serviceClass="com.hanjun.service.HelloWorld" address="/HelloWorld">
  <jaxws:serviceBean>
   <!-- 要暴露的 bean 的引用 -->
   <bean id="helloWorldImpl" class="com.hanjun.service.HelloWorldImpl"></bean>
  </jaxws:serviceBean>
 </jaxws:server>
 
</beans>

说明:jaxws:endpoint 和 jaxws:server 都可以发布服务

3.web.xml

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:applicationContext.xml</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 
 <servlet>
  <servlet-name>CXFService</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>CXFService</servlet-name>
  <url-pattern>/services/*</url-pattern>
 </servlet-mapping>

4.客户端spring配置文件:

 <jaxws:client id="helloWorldClient"
     address="http://localhost:8090/CXFTest/services/HelloWorld"
     serviceClass="com.hanjun.service.HelloWorld"/>

5.测试

  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  HelloWorld helloWorld = context.getBean("helloWorldClient",HelloWorld.class);

6.JAX-RS 在cxf+spring中的应用。修改HelloWorld接口,添加一些注解

@Path("/helloWorld")
@Produces(MediaType.APPLICATION_JSON)
public interface HelloWorld {

 @GET
 @Path("/sayHi/{text}")
    String sayHi(@PathParam("text")String text);

 @GET
 @Path("/sayHiToUser")
    User sayHiToUser(@QueryParam("")User user);

applicationContext.xml中添加配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jaxws="http://cxf.apache.org/jaxws"
 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
 xsi:schemaLocation="Index of /schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://cxf.apache.org/jaxws
           http://cxf.apache.org/schemas/jaxws.xsd
           http://cxf.apache.org/jaxrs 
       
http://cxf.apache.org/schemas/jaxrs.xsd">
 ...

 <bean id="helloWorld" class="com.hanjun.service.HelloWorldImpl"></bean>
 <jaxrs:server address="/jaxrs">
     <jaxrs:serviceBeans>
      <!-- 要暴露的 bean 的引用 -->
      <ref bean="helloWorld"/>
     </jaxrs:serviceBeans>
 </jaxrs:server>
 ...

测试页面:

 <script type="text/javascript" src="jquery-2.0.3.min.js"></script>
 <script type="text/javascript">
  function sayHi(){
   $.get("/CXFTest/services/jaxrs/helloWorld/sayHi/dsfsd",null,function(result){
    alert(result);
   },'text');
  }
  function sayHiToUser(){
   $.get("/CXFTest/services/jaxrs/helloWorld/sayHiToUser",{name:"zh"},function(result){
    alert(result.user.name);
   },'json');
  }
 </script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值