基于反射实现自动化restful开发,自动化restful开发


[Author]: kwu 

基于反射实现自动化restful开发,通用的只需要写查询数据库的sql,并加入对应的javabean实现的快速restful服务的开发。


1、编写数据库的查询sql,对应sql.properties

daily = DailyReport;select t.day,t.cnt,t.type from (select day,cnt,type From dailyreport where type=? order by day desc limit ? ) t order by t.day;String,Integer

SQL的属性文件,以";"分隔。说明:

1)pv为该SQL的标签。

2)第一个参数为,DailyReport为对应的JavaBean的类名

3)第二个参数为查询的SQL,参数以 "?" 占位符

4)第三个参数为 参数的类型,以"," 分隔


2、编写对应的pojo类

import com.hexun.bean.base.ChartsData;

public class DailyReport implements ChartsData {
	private String day, type;
	private Integer cnt;

	public String getDay() {
		return day;
	}

	public void setDay(String day) {
		this.day = day;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Integer getCnt() {
		return cnt;
	}

	public void setCnt(Integer cnt) {
		this.cnt = cnt;
	}
}

3、启动restful服务访问

http://localhost:9088/restful?tag=pv&args=3

<img src="http://img.blog.csdn.net/20150709152633218?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />


附反射DAO实现:

package com.hexun.dao;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hexun.bean.base.AttrData;
import com.hexun.bean.base.ChartsData;
import com.hexun.utils.DbUtil;
import com.hexun.utils.GetSqlStatement;

@SuppressWarnings("rawtypes")
public class ChartDao {
	private static DbUtil dbUtil = new DbUtil();

	public static List<ChartsData> getRestData(String tag, String[] args) throws Exception {
		Connection con = dbUtil.getCon();
		String content = GetSqlStatement.getSql(tag);
		
		if(content==null){
			return new ArrayList<ChartsData>();
		}
		
		String splited[] = content.split(";");

		String className = splited[0];
		String sql = splited[1];

		Class clazz = Class.forName("com.hexun.bean." + className);

		List<AttrData> listAttr = getClassAttrs(clazz);

		PreparedStatement pstmt = con.prepareStatement(sql);

		if (splited.length == 3) {
			String type = splited[2];
			int idx = 1;
			String[] types = type.split(",");
			for (int i = 0; i < types.length; i++) {
				if (types[i].trim().equalsIgnoreCase("String")) {
					pstmt.setString(idx, args[i]);
				}
				if (types[i].trim().equalsIgnoreCase("Integer")) {
					String tmp = args[i];
					int intVal = Integer.parseInt(tmp);
					pstmt.setInt(idx, intVal);
				}
				idx++;
			}
		}

		ResultSet rs = pstmt.executeQuery();
		List<ChartsData> listData = new ArrayList<ChartsData>();

		while (rs.next()) {
			ChartsData bean = (ChartsData) clazz.newInstance();
			for (AttrData attribute : listAttr) {
				Field f1 = clazz.getDeclaredField(attribute.getName());
				String attrType = attribute.getType();

				if ("class java.lang.Integer".equals(attrType)) {
					Integer val = rs.getInt(attribute.getName());
					f1.setAccessible(true);
					f1.set(bean, val);
				} else {
					String val = rs.getString(attribute.getName());
					f1.setAccessible(true);
					f1.set(bean, val);
				}

			}
			listData.add(bean);
		}

		dbUtil.close(rs, pstmt, con);

		return listData;
	}

	/**
	 * 获取类的属性集合
	 * 
	 * @param listAttr
	 * @param clazz
	 */
	private static List<AttrData> getClassAttrs(Class clazz) {
		List<AttrData> listAttr = new ArrayList<AttrData>();
		Field[] fieldlist = clazz.getDeclaredFields();
		for (int i = 0; i < fieldlist.length; i++) {
			AttrData data = new AttrData();
			Field fld = fieldlist[i];

			String type = fld.getType().toString();
			String name = fld.getName();
			data.setName(name);
			data.setType(type);

			listAttr.add(data);
		}
		System.out.println(listAttr);
		return listAttr;
	}

	/**
	 * Rest数据转换成list
	 * 
	 * @param restData
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static Map<String, List> getRestDataForList(List<ChartsData> restData, String tag) throws Exception {
		Map<String, List> map = new HashMap<String, List>();
		String content = GetSqlStatement.getSql(tag);
		String splited[] = content.split(";");
		String className = splited[0];

		Class clazz = Class.forName("com.hexun.bean." + className);
		List<AttrData> listAttr = getClassAttrs(clazz);

		for (AttrData attribute : listAttr) {

			String attrType = attribute.getType();

			if ("class java.lang.Integer".equals(attrType)) {
				List<Integer> listData = new ArrayList<Integer>();
				for (ChartsData data : restData) {
					Field f1 = clazz.getDeclaredField(attribute.getName());
					f1.setAccessible(true);
					Object object = f1.get(data);
					listData.add((object == null) ? 0 : Integer.parseInt(object.toString()));

				}
				map.put(attribute.getName(), listData);
			} else {
				List<String> listData = new ArrayList<String>();

				for (ChartsData data : restData) {
					Field f1 = clazz.getDeclaredField(attribute.getName());
					f1.setAccessible(true);
					Object object = f1.get(data);
					listData.add((object == null) ? "" : object.toString());
				}
				map.put(attribute.getName(), listData);
			}

		}

		return map;
	}

	public static void main(String[] args) throws Exception {
		List<ChartsData> restData = ChartDao.getRestData("newsclick", new String[] { "hour_trend", "15" });
		System.out.println(restData);

		// Map<String, List> restDataForList =
		// ChartDao.getRestDataForList(restData, "daily");
		// System.out.println(restDataForList);
	}

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关内容