好一段时间都在做接口,以前有用axis2来做接口,后面在项目中有接触到cxf,看了相关的文档,个人就觉得,cxf做接口挺爽的,个人空闲时就开始了对cxf的学习。学习新的技术,新的语言,个人喜欢首先看demo,先把程序跑起来、看看效果,一般demo引入工程或多或少多会出点问题,可能是环境问题、少jar、版本不一致、与原有工程的东西冲突,等等。
cxf也有提供的样例,笔记中给出的样例比较简单易懂,记下笔记也是供后面用到这方面的技术,能快速使用上手。
开发环境:eclipse-jee-kepler-R-win32、jdk-7u3-windows-i586、内嵌web应用服务器jetty。
这是个maven项目,相关的项目定义、依赖由maven管理,样例结构预览:
cxf使用aegis绑定数据,自己主要关心服务代码的实现,aegis负责生成xml schema/wsdl xml,aegis测试项目主要提供了一个接口LuckyService,两个方法:获取城市天气、保存城市天气。
1、LuckyService代码清单
/**
* LuckyService.java
* com.toplucky.server
* Function:(一句话功能说明)
* version date author
* ──────────────────────────────────────
* Ver 1.0 2014年8月13日 CWL
* Copyright(c) 2014, happyweekend All Rights Reserved.
*/
package com.toplucky.server;
/**
* (一句话功能说明)
* @author CWL
* @version 1.0
* @see
* @since 1.0
* @Date 2014年8月13日 上午10:53:20
*/
public interface LuckyService {
/**
* getCityWeather:获取城市天气
* @param cityCode 城市code
* @return
*/
Weather getCityWeather(String cityCode);
/**
* saveWeather:新增
* @param weather
* @return
*/
boolean saveWeather(Weather weather);
}
2、接口实现LuckyServiceImpl代码清单
/**
* LuckyServiceImpl.java
* com.toplucky.server
* Function:(一句话功能说明)
* version date author
* ──────────────────────────────────────
* Ver 1.0 2014年8月13日 CWL
* Copyright(c) 2014, happyweekend All Rights Reserved.
*/
package com.toplucky.server;
import java.util.Date;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* (一句话功能说明)
* @author CWL
* @version 1.0
* @see
* @since 1.0
* @Date 2014年8月13日 上午11:13:07
*/
public class LuckyServiceImpl implements LuckyService {
private static final Logger logger = LoggerFactory.getLogger(LuckyServiceImpl.class);
@Override
public Weather getCityWeather(String cityCode) {
Weather weather = new Weather();
String uri = "http://www.weather.com.cn/data/cityinfo/" + cityCode + ".html";
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(uri);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
logger.error("Method failed: " + getMethod.getStatusLine());
}
byte[] responseBody = getMethod.getResponseBody();
String responseStr = new String(responseBody);
JSONObject jsonObject = JSONObject.fromObject(responseStr);
Object temp = jsonObject.get("weatherinfo");
if (temp instanceof JSONObject){
JSONObject wtInfo = (JSONObject) temp;
//"temp1":"0℃","temp2":"10℃",
boolean temp1Lower = false;
String temp1 = wtInfo.get("temp1") + "";
String temp2 = wtInfo.get("temp2") + "";
StringBuilder wtBuilder = new StringBuilder();
wtBuilder.append(wtInfo.get("city")).append(" ")
.append(wtInfo.get("weather")).append(" ");
if (temp1.length() < temp2.length()) temp1Lower = true;
else if (temp1.length() == temp2.length()) {
if (temp1.compareTo(temp2) <= 0) temp1Lower = true;
}
if (temp1Lower) wtBuilder.append(temp1).append("~").append(temp2);
else wtBuilder.append(temp2).append("~").append(temp1);
weather.setDesc(wtBuilder.toString());
weather.setTime(DateUtil.formatDate(new Date(), "yyyy年MM月dd日 HH:mm"));
}
} catch (Exception e){
e.printStackTrace();
} finally {
getMethod.releaseConnection();
}
return weather;
}
@Override
public boolean saveWeather(Weather weather) {
logger.info("call saveWeather...");
logger.info("saveWeather.time=" + weather.getTime());
logger.info("saveWeather.weather=" + weather.getDesc());
return true;
}
}
3、气候Weather代码清单
/**
* Weather.java
* com.toplucky.server
* Function:(一句话功能说明)
* version date author
* ──────────────────────────────────────
* Ver 1.0 2014年8月13日 CWL
*
* Copyright(c) 2014, happyweekend All Rights Reserved.
*/
package com.toplucky.server;
/**
* (一句话功能说明)
* @author CWL
* @version 1.0
* @see
* @since 1.0
* @Date 2014年8月13日 上午10:58:52
*/
public class Weather {
// 2013年12月25日 11:52
private String time;
// 成都 阴 10 ℃~ 0 ℃
private String desc;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "Weather [time=" + time + ", desc=" + desc + "]";
}
}
这样一个获取天气的接口代码就算完成了,这里需要根据接口LuckyService配置aegis的一个文件LuckyService.aegis.xml,
相关配置会在生成的WSDL中体现
4、LuckyService.aegis.xml代码清单
<?xml version="1.0" encoding="UTF-8"?>
<mappings>
<mapping name="LuckyService">
<method name="getCityWeather">
<parameter index="0" mappedName="cityCode" nillable='false' />
</method>
<method name="saveWeather">
<parameter index="0" mappedName="weather" nillable='false' />
</method>
</mapping>
</mappings>
这样发布一个接口的准备工作已完成,接下来就是将接口发布出来供外部调用
5、发布接口类LuckyServer代码清单
/**
* LuckyServer.java
* com.toplucky.server
*
* Function:(一句话功能说明)
*
* version date author
* ──────────────────────────────────────
* Ver 1.0 2014年8月13日 CWL
*
* Copyright(c) 2014, happyweekend All Rights Reserved.
*/
package com.toplucky.server;
import org.apache.cxf.aegis.databinding.AegisDatabinding;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* (一句话功能说明)
* @author CWL
* @version 1.0
* @see
* @since 1.0
* @Date 2014年8月13日 下午2:21:26
*/
public class LuckyServer {
private static final Logger logger = LoggerFactory.getLogger(LuckyServer.class);
public static void main(String[] args) throws InterruptedException {
LuckyServiceImpl luckyServiceImpl = new LuckyServiceImpl();
ServerFactoryBean svrFactory = new ServerFactoryBean();
svrFactory.setServiceClass(LuckyService.class);
svrFactory.setAddress("http://localhost:8089/lucky");
svrFactory.setServiceBean(luckyServiceImpl);
svrFactory.getServiceFactory().setDataBinding(new AegisDatabinding());
svrFactory.create();
logger.info("LuckyServer ready...");
}
}
6、客户端测试类LuckyClient代码清单
/**
* LuckyClient.java
* com.toplucky.client
*
* Function:(一句话功能说明)
* version date author
* ──────────────────────────────────────
* Ver 1.0 2014年8月13日 CWL
* Copyright(c) 2014, happyweekend All Rights Reserved.
*/
package com.toplucky.client;
import org.apache.cxf.aegis.databinding.AegisDatabinding;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.toplucky.server.LuckyService;
import com.toplucky.server.Weather;
/**
* (一句话功能说明)
*
* @author CWL
* @version 1.0
* @see
* @since 1.0
* @Date 2014年8月13日 下午2:14:47
*/
public class LuckyClient {
private static final Logger logger = LoggerFactory.getLogger(LuckyClient.class);
public static void main(String args[]) throws Exception {
ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
factory.setAddress("http://localhost:8089/lucky");
factory.getServiceFactory().setDataBinding(new AegisDatabinding());
LuckyService client = factory.create(LuckyService.class);
logger.info("Invoke getCityWeather()....");
Weather weather = client.getCityWeather("101270101");
if (weather != null)
logger.info(weather.toString());
logger.info("Invoke saveWeather()....");
boolean success = client.saveWeather(weather);
logger.info(success + "");
}
}
WSDL地址:http://localhost:8089/lucky?wsdl,使用cxf生成客户端调用类LuckyServicePortType_LuckyServicePort_Client代码清单
package com.toplucky.server;
/**
* Please modify this class to meet your needs
* This class is not complete
*/
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
/**
* This class was generated by Apache CXF 2.7.7
* 2014-08-13T15:11:50.015+08:00
* Generated source version: 2.7.7
*/
public final class LuckyServicePortType_LuckyServicePort_Client {
private static final QName SERVICE_NAME = new QName("http://server.toplucky.com/", "LuckyService");
private LuckyServicePortType_LuckyServicePort_Client() {
}
public static void main(String args[]) throws java.lang.Exception {
URL wsdlURL = LuckyService.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
LuckyService ss = new LuckyService(wsdlURL, SERVICE_NAME);
LuckyServicePortType port = ss.getLuckyServicePort();
{
System.out.println("Invoking getCityWeather...");
java.lang.String _getCityWeather_cityCode = "101270101";
com.toplucky.server.Weather _getCityWeather__return = port.getCityWeather(_getCityWeather_cityCode);
System.out.println("getCityWeather.time=" + _getCityWeather__return.getTime().getValue());
System.out.println("getCityWeather.desc=" + _getCityWeather__return.getDesc().getValue());
}
{
QName _WeatherDesc_QNAME = new QName("http://server.toplucky.com", "desc");
QName _WeatherTime_QNAME = new QName("http://server.toplucky.com", "time");
System.out.println("Invoking saveWeather...");
com.toplucky.server.Weather _saveWeather_weather = new com.toplucky.server.Weather();
javax.xml.bind.JAXBElement<java.lang.String> _saveWeather_weatherTime = new JAXBElement<String>(_WeatherTime_QNAME, String.class, "2014年08月13日 07:22");
_saveWeather_weather.setTime(_saveWeather_weatherTime);
javax.xml.bind.JAXBElement<java.lang.String> _saveWeather_weatherDesc = new JAXBElement<String>(_WeatherDesc_QNAME, String.class, "成都 多云 21℃~31℃");
_saveWeather_weather.setDesc(_saveWeather_weatherDesc);
boolean _saveWeather__return = port.saveWeather(_saveWeather_weather);
System.out.println("saveWeather.result=" + _saveWeather__return);
}
System.exit(0);
}
}
cxf绑定aegis发布服务简单、快速,接口以及接口调用客户端所有代码都已上传
地址:http://download.csdn.net/detail/check_null/7753161