JDBC 实现数据持久层框架(一)
现在mybatis已经很流行了,其实如果熟悉java的动态代理和注解等,自己也很容易实现类似于mybatis的框架,我们一步步来:
一,定义注解.
1,@Command,表示一个执行的sql命令,可重复注解
1 package com.jjh.spider; 2 3 import java.lang.annotation.ElementType; 4 import java.lang.annotation.Repeatable; 5 import java.lang.annotation.Retention; 6 import java.lang.annotation.RetentionPolicy; 7 import java.lang.annotation.Target; 8 9 /** 10 * @author Administrator 11 * 12 */ 13 @Target(ElementType.METHOD) 14 @Retention(RetentionPolicy.RUNTIME) 15 @Repeatable(Commands.class) 16 public @interface Command { 17 String value(); 18 boolean commit() default true; 19 }
2,@Commands,跟@Command匹配
1 /** 2 * 3 */ 4 package com.jjh.spider; 5 6 import java.lang.annotation.ElementType; 7 import java.lang.annotation.Retention; 8 import java.lang.annotation.RetentionPolicy; 9 import java.lang.annotation.Target; 10 11 /** 12 * @author Administrator 13 * 14 */ 15 @Target(ElementType.METHOD) 16 @Retention(RetentionPolicy.RUNTIME) 17 public @interface Commands { 18 Command[] value() default{}; 19 }
3,@Param,用来把接口的方法参数和command的参数对应
1 /** 2 * 3 */ 4 package com.jjh.spider; 5 6 import java.lang.annotation.ElementType; 7 import java.lang.annotation.Retention; 8 import java.lang.annotation.RetentionPolicy; 9 import java.lang.annotation.Target; 10 11 /** 12 * @author Administrator 13 * 14 */ 15 @Target({ElementType.PARAMETER}) 16 @Retention(RetentionPolicy.RUNTIME) 17 public @interface Param { 18 String value(); 19 }
4,业务类:JDBC,以动态接口代理的方式实现
1 /** 2 * 3 */ 4 package com.jjh.spider; 5 6 import java.lang.reflect.Array; 7 import java.lang.reflect.InvocationHandler; 8 import java.lang.reflect.InvocationTargetException; 9 import java.lang.reflect.Method; 10 import java.lang.reflect.Parameter; 11 import java.lang.reflect.ParameterizedType; 12 import java.lang.reflect.Proxy; 13 import java.lang.reflect.Type; 14 import java.sql.Connection; 15 import java.sql.PreparedStatement; 16 import java.sql.ResultSet; 17 import java.sql.ResultSetMetaData; 18 import java.sql.SQLException; 19 import java.util.ArrayList; 20 import java.util.HashMap; 21 import java.util.List; 22 import java.util.Map; 23 import java.util.Objects; 24 import java.util.concurrent.atomic.AtomicReference; 25 import java.util.regex.Matcher; 26 import java.util.regex.Pattern; 27 28 import javax.sql.DataSource; 29 30 import org.json.JSONArray; 31 import org.json.JSONException; 32 import org.json.JSONObject; 33 34 import com.jjh.common.Utils; 35 36 /** 37 * @author Administrator 38 * 39 */ 40 public final class JDBC { 41 private static final Pattern pattern = Pattern.compile("#\\{(.+?)\\}"); 42 protected final AtomicReference<DataSource> dataSource; 43 44 /** 45 * @param dataSource 46 */ 47 public JDBC(DataSource dataSource) { 48 super(); 49 this.dataSource = new AtomicReference<DataSource>(dataSource); 50 51 } 52 53 /** 54 * @return the dataSource 55 */ 56 public DataSource getDataSource() { 57 return dataSource.get(); 58 } 59 60 @SuppressWarnings("unchecked") 61 public <T> T newObject(Class<?>... classes){ 62 InvocationHandler handler = new InvocationHandler() { 63 @Override 64 public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Exception { 65 // TODO Auto-generated method stub 66 return call(dataSource.get().getConnection(), arg0, arg1, arg2); 67 } 68 }; 69 return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), classes, handler); 70 } 71 72 public static <T> T newObject(DataSource dataSource, Class<?>... classes){ 73 try{ 74 return newObject(dataSource.getConnection(), classes); 75 } catch (SQLException e) { 76 // TODO Auto-generated catch block 77 e.printStackTrace(); 78 } 79 return null; 80 } 81 82 @SuppressWarnings("unchecked") 83 public static <T> T newObject(Connection conn, Class<?>... classes) { 84 InvocationHandler handler = new InvocationHandler() { 85 @Override 86 public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Exception { 87 // TODO Auto-generated method stub 88 return call(conn, arg0, arg1, arg2); 89 } 90 }; 91 return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), classes, handler); 92 } 93 94 private static Object call(Connection conn, Object arg0, Method arg1, Object[] arg2) throws Exception { 95 // TODO Auto-generated method stub 96 Object ret = null; 97 // 提取方法上面的注解 98 Parameter[] params = arg1.getParameters(); 99 if (arg1.isAnnotationPresent(Command.class)) { 100 Command[] commands = arg1.getAnnotationsByType(Command.class); 101 String sql = commands[0].value(); 102 Matcher m = pattern.matcher(sql); 103 try { 104 PreparedStatement pst = conn.prepareStatement(sql.replaceAll(pattern.pattern(), "?")); 105 if (params.length == 1) { 106 if (List.class.isAssignableFrom(params[0].getType())) { 107 Type type = params[0].getParameterizedType(); 108 if (Objects.nonNull(type)) { 109 ParameterizedType pType = (ParameterizedType) type; 110 Class<?> c = (Class<?>) pType.getActualTypeArguments()[0]; 111 if (!Utils.isPrimitive(c)) { 112 // 批处理,如:List<Person> 113 @SuppressWarnings("unchecked") 114 List<Object> list = List.class.cast(arg2[0]); 115 for (int j = 0; j < list.size(); j++) { 116 for (int i = 0; m.find(); i++) { 117 String attr = m.group(1);//.replace("#", "").replace("{", "").replace("}", ""); 118 pst.setObject(i + 1, get(list.get(j), attr)); 119 } 120 pst.execute(); 121 pst.clearParameters(); 122 123 } 124 } 125 } 126 } else if (params[0].getType() == JSONObject.class) { 127 JSONObject json = (JSONObject) arg2[0]; 128 for (int i = 0; m.find(); i++) { 129 String attr = m.group(1);//.replace("#", "").replace("{", "").replace("}", ""); 130 pst.setObject(i + 1, json.opt(attr)); 131 } 132 } else if (params[0].getType() == JSONArray.class) { 133 JSONArray array = (JSONArray) arg2[0]; 134 // 批处理,如[{},{},{}] 135 for (int j = 0; j < array.length(); j++) { 136 JSONObject json = array.optJSONObject(j); 137 for (int i = 0; m.find(); i++) { 138 String attr = m.group(1);//.replace("#", "").replace("{", "").replace("}", ""); 139 pst.setObject(i + 1, json.opt(attr)); 140 } 141 pst.execute(); 142 pst.clearParameters(); 143 144 } 145 } else if (Map.class.isAssignableFrom(params[0].getType())) { 146 for (int i = 0; m.find(); i++) { 147 String attr = m.group(1);//.replace("#", "").replace("{", "").replace("}", ""); 148 pst.setObject(i + 1, Map.class.getMethod("get", String.class).invoke(arg2[0], attr)); 149 } 150 } else if (params[0].getType().isArray() || params[0].isVarArgs()) { 151 Class<?> elem = params[0].getType().getComponentType(); 152 if (!Utils.isPrimitive(elem)) { 153 for (int j = 0; j < Array.getLength(arg2[0]); j++) { 154 for (int i = 0; m.find(); i++) { 155 String attr = m.group(1);//.replace("#", "").replace("{", "").replace("}", ""); 156 pst.setObject(i + 1, get(Array.get(arg2[0], j), attr)); 157 } 158 pst.execute(); 159 pst.clearParameters(); 160 161 } 162 } 163 } else if (!Utils.isPrimitive(params[0].getType())) { 164 165 for (int i = 0; m.find(); i++) { 166 String attr = m.group(1);//.replace("#", "").replace("{", "").replace("}", ""); 167 pst.setObject(i + 1, get(arg2[0], attr)); 168 } 169 170 } else if (Utils.isPrimitive(params[0].getType())) { 171 pst.setObject(1, arg2[0]); 172 } 173 } else if (params.length > 1) { 174 for (int i = 0; m.find(); i++) { 175 String attr = m.group(1);//.replace("#", "").replace("{", "").replace("}", ""); 176 int index = index(arg1, attr); 177 if (index > -1) 178 pst.setObject(i + 1, arg2[index]); 179 else if (index == -1) 180 pst.setObject(i + 1, null); 181 182 } 183 184 } 185 if (pst.execute()) { 186 ResultSet res = pst.getResultSet(); 187 ret = handleResultSet(arg1, res); 188 res.close(); 189 pst.close(); 190 } 191 else 192 { 193 ret=pst.getUpdateCount(); 194 } 195 } finally { 196 if (Objects.nonNull(conn) && !conn.isClosed()) 197 conn.close(); 198 } 199 } 200 201 return ret; 202 } 203 204 @SuppressWarnings({ "rawtypes" }) 205 protected static Object handleResultSet(Method method, ResultSet resultSet) 206 throws SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException, 207 SQLException, JSONException, InvocationTargetException { 208 // TODO Auto-generated method stub 209 Type type = method.getGenericReturnType(); 210 // 处理非参数化类型 211 if (type instanceof Class) { 212 Class<?> c = (Class<?>) type; 213 if (Utils.isPrimitive(c)) { 214 return usePrimitiveType(resultSet); 215 } 216 // 转化成JSONArray数据 217 else if (JSONArray.class.isAssignableFrom(c)) { 218 return useJSONArray(resultSet); 219 } 220 // 转化成JSONObject数据 221 else if (JSONObject.class.isAssignableFrom(c)) { 222 return userJSONObject(resultSet); 223 } 224 // 使用擦除的List 225 else if (List.class.isAssignableFrom(c)) { 226 List list = c == List.class ? new ArrayList() : (List) c.newInstance(); 227 useRawList(list, resultSet); 228 return list; 229 } 230 // 使用擦除的Map 231 else if (Map.class.isAssignableFrom(c)) { 232 Map map = c == Map.class ? new HashMap() : (Map) c.newInstance(); 233 useRawMap(map, resultSet); 234 return map; 235 } 236 // 使用自定义的实体类 237 else { 238 return useBeanObject(c, resultSet); 239 } 240 } 241 // 处理参数化类型 242 else if (type instanceof ParameterizedType) { 243 ParameterizedType c = (ParameterizedType) type; 244 Class<?> rawType = (Class<?>) c.getRawType(); 245 if (List.class.isAssignableFrom(rawType)) { 246 List list = rawType == List.class ? new ArrayList() : (List) rawType.newInstance(); 247 useParameterizedList(list, (Class<?>) c.getActualTypeArguments()[0], resultSet); 248 return list; 249 } else if (Map.class.isAssignableFrom(rawType)) { 250 Class<?> keyType = (Class<?>) c.getActualTypeArguments()[0]; 251 Class<?> valueType = (Class<?>) c.getActualTypeArguments()[1]; 252 if (keyType == String.class && valueType == Object.class) { 253 Map map = rawType == Map.class ? new HashMap() : (Map) rawType.newInstance(); 254 useRawMap(map, resultSet); 255 return map; 256 } 257 } 258 } 259 return null; 260 } 261 262 private static Object usePrimitiveType(ResultSet resultSet) throws SQLException { 263 // TODO Auto-generated method stub 264 if (resultSet.next()) 265 return resultSet.getObject(1); 266 return null; 267 } 268 269 private static JSONArray useJSONArray(ResultSet resultSet) throws JSONException, SQLException { 270 // TODO Auto-generated method stub 271 JSONArray ret = new JSONArray(); 272 ResultSetMetaData meta = resultSet.getMetaData(); 273 for (; resultSet.next();) { 274 JSONObject obj = new JSONObject(); 275 for (int i = 1; i <= meta.getColumnCount(); i++) { 276 obj.put(meta.getColumnLabel(i), resultSet.getObject(i)); 277 } 278 ret.put(obj); 279 } 280 return ret; 281 } 282 283 private static JSONObject userJSONObject(ResultSet resultSet) throws JSONException, SQLException { 284 // TODO Auto-generated method stub 285 JSONObject ret = new JSONObject(); 286 ResultSetMetaData meta = resultSet.getMetaData(); 287 for (; resultSet.next();) { 288 for (int i = 1; i <= meta.getColumnCount(); i++) { 289 ret.put(meta.getColumnLabel(i), resultSet.getObject(i)); 290 } 291 292 } 293 return ret; 294 } 295 296 @SuppressWarnings({ "unchecked", "rawtypes" }) 297 private static void useRawList(List ret, ResultSet resultSet) throws SQLException { 298 // TODO Auto-generated method stub 299 // 从中获取resultset的结构信息 300 ResultSetMetaData meta = resultSet.getMetaData(); 301 for (; resultSet.next();) { 302 Map<String, Object> map = new HashMap<>(); 303 for (int i = 1; i <= meta.getColumnCount(); i++) 304 map.put(meta.getColumnLabel(i), resultSet.getObject(i)); 305 ret.add(map); 306 } 307 308 } 309 310 @SuppressWarnings({ "unchecked", "rawtypes" }) 311 private static void useRawMap(Map ret, ResultSet resultSet) throws SQLException { 312 // TODO Auto-generated method stub 313 ResultSetMetaData meta = resultSet.getMetaData(); 314 if (resultSet.next()) { 315 for (int i = 1; i <= meta.getColumnCount(); i++) 316 ret.put(meta.getColumnLabel(i), resultSet.getObject(i)); 317 } 318 } 319 320 private static Object useBeanObject(Class<?> c, ResultSet resultSet) throws SecurityException, SQLException, 321 IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { 322 // TODO Auto-generated method stub 323 if (resultSet.next()) { 324 // 从中获取resultset的结构信息 325 ResultSetMetaData meta = resultSet.getMetaData(); 326 return getBean(meta, c, resultSet); 327 } 328 return null; 329 } 330 331 @SuppressWarnings({ "rawtypes", "unchecked" }) 332 private static void useParameterizedList(List ret, Class<?> type, ResultSet resultSet) 333 throws SQLException, SecurityException, IllegalArgumentException, IllegalAccessException, 334 InstantiationException, JSONException, InvocationTargetException { 335 // TODO Auto-generated method stub 336 if (!Utils.isPrimitive(type)) { 337 ResultSetMetaData meta = resultSet.getMetaData(); 338 for (; resultSet.next();) { 339 ret.add(getBean(meta, type, resultSet)); 340 } 341 } 342 } 343 344 private static Object getBean(ResultSetMetaData meta, Class<?> c, ResultSet resultSet) 345 throws InstantiationException, IllegalAccessException, SecurityException, IllegalArgumentException, 346 InvocationTargetException, SQLException { 347 // TODO Auto-generated method stub 348 Object obj = c.newInstance(); 349 for (int col = 1; col <= meta.getColumnCount(); col++) { 350 Object val = resultSet.getObject(col); 351 Method m = getSetMethod(c, val.getClass(), meta.getColumnLabel(col)); 352 if (Objects.nonNull(m)) 353 m.invoke(obj, val); 354 } 355 return obj; 356 } 357 358 private static Method getSetMethod(Class<?> c, Class<?> paramType, String prop) { 359 // TODO Auto-generated method stub 360 prop = Character.toUpperCase(prop.charAt(0)) + prop.substring(1, prop.length()); 361 Method m; 362 try { 363 m = c.getMethod("set" + prop, paramType); 364 } catch (NoSuchMethodException e) { 365 // TODO Auto-generated catch block 366 m = null; 367 } 368 return m; 369 } 370 371 private static int index(Method m, String attr) { 372 // TODO Auto-generated method stub 373 Parameter[] params = m.getParameters(); 374 for (int i = 0; i < params.length; i++) { 375 if (params[i].isAnnotationPresent(Param.class)) { 376 Param p = params[i].getAnnotation(Param.class); 377 if (p.value().equals(attr)) 378 return i; 379 } 380 381 } 382 return -1; 383 } 384 385 private static Object get(Object object, String attr) throws NoSuchMethodException, SecurityException, 386 IllegalAccessException, IllegalArgumentException, InvocationTargetException { 387 // TODO Auto-generated method stub 388 attr = Character.toUpperCase(attr.charAt(0)) + attr.substring(1, attr.length()); 389 Method m = null; 390 try { 391 m = object.getClass().getMethod("get" + attr); 392 } catch (NoSuchMethodException e) { 393 // TODO Auto-generated catch block 394 m = object.getClass().getMethod("is" + attr); 395 } 396 return m.invoke(object); 397 } 398 399 }
5,关联的工具类
1 /** 2 * 3 */ 4 package com.jjh.common; 5 6 import java.lang.reflect.Method; 7 import java.math.BigDecimal; 8 import java.net.URL; 9 import java.text.SimpleDateFormat; 10 import java.util.Date; 11 import java.util.Iterator; 12 import java.util.Locale; 13 import org.json.JSONArray; 14 import org.json.JSONException; 15 import org.json.JSONObject; 16 17 /** 18 * @author Administrator 19 * 20 */ 21 public class Utils { 22 23 /** 24 * 25 */ 26 private Utils() { 27 // TODO Auto-generated constructor stub 28 } 29 30 @SuppressWarnings("unchecked") 31 public static <T>T convert(Class<?> c, String value){ 32 // TODO Auto-generated method stub 33 Object ret=value; 34 if (c == int.class || c == Integer.class) 35 ret=new Integer(value); 36 else if (c == short.class || c == Short.class) 37 ret=new Short(value); 38 else if (c == long.class || c == Long.class) 39 ret=new Long(value); 40 else if (c == float.class || c == Float.class) 41 ret=new Float(value); 42 else if (c == double.class || c == Double.class) 43 ret=new Double(value); 44 else if (c == byte.class || c == Byte.class) 45 ret=new Byte(value); 46 else if (c == boolean.class || c == Boolean.class) 47 ret=new Boolean(value); 48 else if (c == java.math.BigDecimal.class) 49 ret=new BigDecimal(value); 50 else if (c == java.util.Date.class) 51 ret= parse(value); 52 return (T)ret; 53 } 54 55 @SuppressWarnings("unchecked") 56 public static <T>T convert(String type, String value){ 57 // TODO Auto-generated method stub 58 Object ret=value; 59 switch(type.toLowerCase()) 60 { 61 case "int":ret=new Integer(value);break; 62 case "short":ret=new Short(value);break; 63 case "long":ret=new Long(value);break; 64 case "float":ret=new Float(value);break; 65 case "double":ret=new Double(value);break; 66 case "byte":ret=new Byte(value);break; 67 case "boolean":ret=new Boolean(value);break; 68 case "bigdecimal":ret=new BigDecimal(value);break; 69 case "string":ret=value;break; 70 case "date":ret=parse(value);break; 71 } 72 return (T)ret; 73 } 74 75 public static boolean isPrimitive(Class<?> c) { 76 return c == String.class || c.isPrimitive() 77 || c.getSuperclass() == Number.class || c == Boolean.class 78 || Utils.isAncestor(java.util.Date.class, c) 79 || c == java.math.BigDecimal.class || c==java.sql.Blob.class || c.isArray() && c.getComponentType().isPrimitive(); 80 } 81 82 public static String getSetMethodName(String property) 83 { 84 return "set"+Character.toUpperCase(property.charAt(0))+property.substring(1); 85 } 86 87 public static Method getPublicMethod(Class<?> owner,String methodName) 88 { 89 for(Method m:owner.getMethods()) 90 { 91 if(methodName.equals(m.getName())) 92 return m; 93 } 94 return null; 95 } 96 97 public static double add(double v1, double v2) { 98 BigDecimal b1 = new BigDecimal(Double.toString(v1)); 99 BigDecimal b2 = new BigDecimal(Double.toString(v2)); 100 return b1.add(b2).doubleValue(); 101 } 102 103 public static double sub(double v1, double v2) { 104 BigDecimal b1 = new BigDecimal(Double.toString(v1)); 105 BigDecimal b2 = new BigDecimal(Double.toString(v2)); 106 return b1.subtract(b2).doubleValue(); 107 } 108 109 public static double mul(double v1, double v2) { 110 BigDecimal b1 = new BigDecimal(Double.toString(v1)); 111 BigDecimal b2 = new BigDecimal(Double.toString(v2)); 112 return b1.multiply(b2).doubleValue(); 113 } 114 115 public static double div(double v1, double v2, int scale) { 116 if (scale < 0) { 117 throw new IllegalArgumentException( 118 "The scale must be a positive integer or zero"); 119 } 120 BigDecimal b1 = new BigDecimal(Double.toString(v1)); 121 BigDecimal b2 = new BigDecimal(Double.toString(v2)); 122 return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); 123 } 124 125 public static double round(double value, int decimal) { 126 double v = ((long) (value * Math.pow(10, decimal) + 0.5)) 127 * Math.pow(10, -decimal); 128 String s = String.valueOf(v); 129 int i = s.indexOf('.'); 130 return Double.valueOf((i >= 0 ? s.substring(0, 131 i + 3 < s.length() ? i + 3 : s.length()) : s)); 132 } 133 134 public static boolean isAncestor(Class<?> c1, Class<?> c2) { 135 boolean yes = c2 == c1; 136 for (; c2!=null&&!yes; yes = c2 == c1) 137 c2 = c2.getSuperclass(); 138 return yes; 139 } 140 141 public static String format(java.util.Date date, boolean isTime) { 142 SimpleDateFormat sdf = new SimpleDateFormat( 143 isTime ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd", Locale.CHINA); 144 return sdf.format(date); 145 } 146 147 public static java.util.Date parse(String date){ 148 boolean isTime = false; 149 if (date.length() > 10) 150 isTime = true; 151 SimpleDateFormat sdf = new SimpleDateFormat( 152 isTime ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd", Locale.CHINA); 153 try{ 154 return sdf.parse(date); 155 } 156 catch(Exception e) 157 { 158 return null; 159 } 160 } 161 162 public static long getBeiJinTime() { 163 try { 164 java.net.URL url = new URL("http://www.bjtime.cn"); 165 java.net.URLConnection uc = url.openConnection(); 166 uc.connect(); 167 return uc.getDate(); 168 } catch (Exception e) { 169 return new Date().getTime(); 170 } 171 172 } 173 /* 174 public static boolean authenticate(final String subject, 175 final String version) throws Exception { 176 // TODO Auto-generated method stub 177 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); 178 final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 179 180 // Get a Properties object 181 Properties props = System.getProperties(); 182 props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); 183 props.setProperty("mail.pop3.socketFactory.fallback", "false"); 184 props.setProperty("mail.pop3.port", "995"); 185 props.setProperty("mail.pop3.socketFactory.port", "995"); 186 187 Session session = Session.getDefaultInstance(props, null); 188 189 URLName urln = new URLName("pop3", "pop.qq.com", 995, null, 190 "412383550", "pengling20141017"); 191 Store store = session.getStore(urln); 192 Folder inbox = null; 193 try { 194 store.connect(); 195 inbox = store.getFolder("INBOX"); 196 inbox.open(Folder.READ_ONLY); 197 FetchProfile profile = new FetchProfile(); 198 profile.add("X-mailer"); 199 profile.add(FetchProfile.Item.ENVELOPE); 200 Message[] messages = inbox.getMessages(); 201 inbox.fetch(messages, profile); 202 messages = inbox.search(new SearchTerm() { 203 204 @Override 205 public boolean match(Message arg0) { 206 // TODO Auto-generated method stub 207 try { 208 return arg0.getSubject().equals(subject); 209 } catch (MessagingException e) { 210 // TODO Auto-generated catch block 211 e.printStackTrace(); 212 } 213 return false; 214 } 215 216 }, messages); 217 Multipart multipart = (Multipart) messages[0].getContent(); 218 Part p = multipart.getBodyPart(0); 219 String[] content = p.getContent().toString().split(":"); 220 return messages.length == 1 221 && getBeiJinTime() < parse(content[1]).getTime() 222 && version.equals(content[0]); 223 } finally { 224 try { 225 inbox.close(false); 226 } catch (Exception e) { 227 } 228 try { 229 store.close(); 230 } catch (Exception e) { 231 } 232 } 233 234 }*/ 235 236 public static String urlEncoding(String src) { 237 int i; 238 char j; 239 StringBuilder tmp = new StringBuilder(); 240 tmp.ensureCapacity(src.length() * 6); 241 for (i = 0; i < src.length(); i++) { 242 j = src.charAt(i); 243 if (Character.isDigit(j) || Character.isLowerCase(j) 244 || Character.isUpperCase(j)) 245 tmp.append(j); 246 else if (j < 256) { 247 tmp.append("%"); 248 if (j < 16) 249 tmp.append("0"); 250 tmp.append(Integer.toString(j, 16)); 251 } else { 252 tmp.append("%u"); 253 tmp.append(Integer.toString(j, 16)); 254 } 255 } 256 return tmp.toString(); 257 } 258 259 public static String urlDecoding(String src) { 260 StringBuilder tmp = new StringBuilder(); 261 tmp.ensureCapacity(src.length()); 262 int lastPos = 0, pos = 0; 263 char ch; 264 while (lastPos < src.length()) { 265 pos = src.indexOf("%", lastPos); 266 if (pos == lastPos) { 267 if (src.charAt(pos + 1) == 'u') { 268 ch = (char) Integer.parseInt( 269 src.substring(pos + 2, pos + 6), 16); 270 tmp.append(ch); 271 lastPos = pos + 6; 272 } else { 273 ch = (char) Integer.parseInt( 274 src.substring(pos + 1, pos + 3), 16); 275 tmp.append(ch); 276 lastPos = pos + 3; 277 } 278 } else { 279 if (pos == -1) { 280 tmp.append(src.substring(lastPos)); 281 lastPos = src.length(); 282 } else { 283 tmp.append(src.substring(lastPos, pos)); 284 lastPos = pos; 285 } 286 } 287 } 288 return tmp.toString(); 289 } 290 291 public static String serialize(JSONObject param) throws JSONException 292 { 293 StringBuilder buffer=new StringBuilder(); 294 @SuppressWarnings("rawtypes") 295 Iterator it=param.keys(); 296 for(;it.hasNext();) 297 { 298 String key=(String)it.next(); 299 Object o=param.get(key); 300 if(o instanceof JSONArray) 301 { 302 JSONArray array=(JSONArray)o; 303 for(int i=0;i<array.length();i++) 304 buffer.append("&"+key+"="+array.get(i).toString()); 305 306 } 307 else 308 { 309 buffer.append("&"+key+"="+o.toString()); 310 } 311 } 312 return buffer.toString().substring(1); 313 } 314 315 }
json解析代码(百度云盘分享):
http://pan.baidu.com/s/1hszGxV2
六,测试接口
/** * */ package com.wisezone.erp.persistence.classes; import org.json.JSONArray; import org.json.JSONObject; import com.jjh.spider.Command; import com.jjh.spider.Param; /** * @author Administrator * */ public interface ClassManageDAO { @Command("insert into classroom(name,photo) values(#{name},#{filename})") void newRoom(@Param("name")String name, @Param("filename")String filename); @Command("select name,photo from classroom") JSONArray all(); @Command("select count(*) from classroom") long total(); @Command("select count(*) from classroom where name=#{name}") long exist(String name); @Command("delete from classroom where name=#{name}") void delete(String name); @Command("select name,photo from classroom where name=#{name}") JSONObject load(String name); @Command("delete from student where classroom=#{classroom}") void deleteStudents(String classroom); @Command("select name,x0,y0,x1,y1 from student where classroom=#{classroom}") JSONArray loadStudents(String classroom); @Command("insert into student(classroom,name,x0,y0,x1,y1) values(#{classroom},#{name},#{x0},#{y0},#{x1},#{y1})") void add(JSONObject student); }
测试:JDBC.<ClassManageDAO>newObject(conn,ClassManageDAO.class).total();
)