dbutils中实现数据的增删改查的方法,反射常用的方法,绝对路径的写法(杂记)
jsp的三个指令为:page,include,taglib。。。
建立一个jsp文件,建立起绝对路径,使用时,其他jsp文件导入即可
导入方法:<%@ include file="/commons/common.jsp" %> (这个jsp文件在根目录下的commons文件夹下)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <base href="${pageContext.request.scheme }://${pageContext.request.serverName }:${pageContext.request.serverPort }${pageContext.request.contextPath}/"> <!-- 其内容先后为:完全的绝对路径:http://.... -->
反射类:通过反射获取其他类中的属性,方法,父类等...
package com.atguigu.bookstore.reflection.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * 反射的 Utils 函数集合 * 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数 * @author Administrator * */ public class ReflectionUtils { /** * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型 * 如: public EmployeeDao extends BaseDao<Employee, String> * @param clazz * @param index * @return */ @SuppressWarnings("unchecked") public static Class getSuperClassGenricType(Class clazz, int index){ Type genType = clazz.getGenericSuperclass(); if(!(genType instanceof ParameterizedType)){ return Object.class; } Type [] params = ((ParameterizedType)genType).getActualTypeArguments(); if(index >= params.length || index < 0){ return Object.class; } if(!(params[index] instanceof Class)){ return Object.class; } return (Class) params[index]; } /** * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型 * 如: public EmployeeDao extends BaseDao<Employee, String> * @param <T> * @param clazz * @return */ @SuppressWarnings("unchecked") public static<T> Class<T> getSuperGenericType(Class clazz){ return getSuperClassGenricType(clazz, 0); } /** * 循环向上转型, 获取对象的 DeclaredMethod * @param object * @param methodName * @param parameterTypes * @return */ public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){ for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){ try { //superClass.getMethod(methodName, parameterTypes); return superClass.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { //Method 不在当前类定义, 继续向上转型 } //.. } return null; } /** * 使 filed 变为可访问 * @param field */ public static void makeAccessible(Field field){ if(!Modifier.isPublic(field.getModifiers())){ field.setAccessible(true); } } /** * 循环向上转型, 获取对象的 DeclaredField * @param object * @param filedName * @return */ public static Field getDeclaredField(Object object, String filedName){ for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){ try { return superClass.getDeclaredField(filedName); } catch (NoSuchFieldException e) { //Field 不在当前类定义, 继续向上转型 } } return null; } /** * 直接调用对象方法, 而忽略修饰符(private, protected) * @param object * @param methodName * @param parameterTypes * @param parameters * @return * @throws InvocationTargetException * @throws IllegalArgumentException */ public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes, Object [] parameters) throws InvocationTargetException{ Method method = getDeclaredMethod(object, methodName, parameterTypes); if(method == null){ throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]"); } method.setAccessible(true); try { return method.invoke(object, parameters); } catch(IllegalAccessException e) { System.out.println("不可能抛出的异常"); } return null; } /** * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter * @param object * @param fieldName * @param value */ public static void setFieldValue(Object object, String fieldName, Object value){ Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); try { field.set(object, value); } catch (IllegalAccessException e) { System.out.println("不可能抛出的异常"); } } /** * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter * @param object * @param fieldName * @return */ public static Object getFieldValue(Object object, String fieldName){ Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); Object result = null; try { result = field.get(object); } catch (IllegalAccessException e) { System.out.println("不可能抛出的异常"); } return result; } }
需导入dbutils开源包:commons-dbutils-1.3.
jardbutils方法:实现数据库数据的增删改查简便的方法:
package com.atguigu.bookstore.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.atguigu.bookstore.dao.DAO; import com.atguigu.bookstore.dbutils.JDBCUtils; import com.atguigu.bookstore.reflection.utils.ReflectionUtils; import com.atguigu.bookstore.web.ConnectionContext; public class BaseDAO<T> implements DAO<T> { private QueryRunner queryRunner=new QueryRunner(); private Class<T> clazz; public BaseDAO(){ //反射类中的反射方法; clazz=ReflectionUtils.getSuperGenericType(getClass()); } //执行 INSERT 操作, 返回插入后的记录的 ID,使用QueryRunner不能实现有返回值的操作 @Override public long insert(String sql, Object... args) { long id=0; Connection connection=null; PreparedStatement preparedStatement=null; ResultSet resultSet=null; try { connection=ConnectionContext.getInstance().get(); //Statement.RETURN_GENERATED_KEYS,为返回主键 preparedStatement=connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); if(args!=null){ for(int i=0;i<args.length;i++){ preparedStatement.setObject(i+1, args[i]); } } preparedStatement.executeUpdate(); //获取生成的主键值 resultSet=preparedStatement.getGeneratedKeys(); if(resultSet.next()){ id=resultSet.getLong(1); } } catch (Exception e) { e.printStackTrace(); }finally { JDBCUtils.release(resultSet, preparedStatement); } return id; } @Override //执行 UPDATE 操作, 包括 INSERT(但没有返回值), UPDATE, DELETE public void update(String sql, Object... args) { Connection connection=null; try { connection=ConnectionContext.getInstance().get(); queryRunner.update(connection, sql, args); } catch (Exception e) { e.printStackTrace(); } } @Override //执行单条记录的查询操作, 返回与记录对应的类的一个对象 public T query(String sql, Object... args) { Connection connection=null; try { connection=ConnectionContext.getInstance().get(); return queryRunner.query(connection, sql, new BeanHandler<>(clazz), args); } catch (Exception e) { e.printStackTrace(); } return null; } @Override //执行多条记录的查询操作, 返回与记录对应的类的一个 List public List<T> queryForList(String sql, Object... args) { Connection connection = null; try { connection = ConnectionContext.getInstance().get(); return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args); } catch (Exception e) { e.printStackTrace(); } return null; } @Override //执行一个属性或值的查询操作, 例如查询某一条记录的一个字段, 或查询某个统计信息, 返回要查询的值 public <V> V getSingleVal(String sql, Object... args) { Connection connection=null; try { connection=ConnectionContext.getInstance().get(); return (V) queryRunner.query(connection, sql, new ScalarHandler(), args); } catch (Exception e) { e.printStackTrace(); } return null; } @Override //执行批量更新操作 public void batch(String sql, Object[]... params) { Connection connection=null; try { connection=ConnectionContext.getInstance().get(); queryRunner.batch(connection, sql, params); } catch (Exception e) { e.printStackTrace(); } } }