应用Apache CXF 框架的案例 有更新!

2019-01-21

web service 服务端

添加maven依赖

imagepng

首先写一个简单的接口,这里模拟天气预报(只是模拟)

package cn.qingxuange.cxfserver;

import javax.jws.WebService;

/**
 * Copyright (C) 2019 清轩阁
  * 天气接口
  * @Author Coder
 * @Blog www.qingxuange.cn or www.piaoyunge.cn
 * @Date 2019-01-17
 * @Description: cn.qingxuange
 * @Version V1.0
 **/
@WebService
public interface IWeatherService {
  public String info(String city);
}

接口实现类

package cn.qingxuange.cxfserver.impl;

import cn.qingxuange.cxfserver.IWeatherService;

/**
 * Copyright (C) 2019 清轩阁
  *
 * @Author Coder
 * @Blog www.qingxuange.cn or www.piaoyunge.cn
 * @Date 2019-01-17
 * @Description: cn.qingxuange.cxfserver.impl
 * @Version V1.0
 **/public class WeatherService implements IWeatherService {
  @Override
  public String info(String city) {
  if("兰州".equals(city))
 {  return "晴朗";
  }
  return "多云";
  }
}

web.xml 里面配置spring和cxf的过滤器

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
 listener>
 <context-param>
 <param-name>contextConfigLocationparam-name>
 <param-value>classpath*:applicationContext*.xmlparam-value>
 context-param>
  <!-- 配置cxf servlet -->
  <filter>
 <filter-name>cxffilter-name>
 <filter-class>org.apache.cxf.transport.servlet.CXFServletfilter-class>
 filter>
 <filter-mapping>
 <filter-name>cxffilter-name>
 <url-pattern>/ws/*url-pattern>
 filter-mapping>
web-app>

配置spring配置文件

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
 <!-- 天气服务-->
  <bean id="weatherService" class="cn.qingxuange.cxfserver.impl.WeatherService">bean>

  <!-- 发布服务-->
  <jaxws:server address="/weatherService">
 <jaxws:serviceBean>
 <ref bean="weatherService">ref>
 jaxws:serviceBean>
 jaxws:server>
beans>

访问http://localhost:9090/cxf/ws/weatherService?wsdl

imagepng

下面开始客户端

用java自带工具wsimort

imagepng

生成客户端代码

配置spring

<!--address 里面配置刚才地址栏里的地址-->
<jaxws:client id="weatherClient" address="http://localhost:9090/cxf/ws/weatherService?wsdl"
  serviceClass="cn.qingxuange.cxfserver.impl.IWeatherService">
jaxws:client>

测试方法,打印结果

imagepng

评论
发表评论
validate
取消