diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Autowired.java b/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Autowired.java deleted file mode 100644 index aabf012082b1261f7120672b84491cd02f816569..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Autowired.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.lagou.edu.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target({ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Autowired { -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Service.java b/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Service.java deleted file mode 100644 index 02303b51665ca3e0d40ab854c8b354a1ba0e9d8a..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Service.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.lagou.edu.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Service { - String value() default ""; -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Transactional.java b/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Transactional.java deleted file mode 100644 index 5c529119ec5f8af06d90c74393cb5319e31c84d1..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Transactional.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.lagou.edu.annotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -public @interface Transactional { -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/dao/AccountDao.java b/code/lagou-transfer/src/main/java/com/lagou/edu/dao/AccountDao.java deleted file mode 100755 index 462ad14477d321c9c0c6512d0dfcce25b7f8a9b4..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/dao/AccountDao.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.lagou.edu.dao; - -import com.lagou.edu.pojo.Account; - -/** - * @author 应癫 - */ -public interface AccountDao { - - Account queryAccountByCardNo(String cardNo) throws Exception; - - int updateAccountByCardNo(Account account) throws Exception; -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/dao/impl/JdbcAccountDaoImpl.java b/code/lagou-transfer/src/main/java/com/lagou/edu/dao/impl/JdbcAccountDaoImpl.java deleted file mode 100755 index 5cd5f91c1a76d38028ae0dceb5ae0b6af84291ca..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/dao/impl/JdbcAccountDaoImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.lagou.edu.dao.impl; - -import com.lagou.edu.annotation.Autowired; -import com.lagou.edu.annotation.Repository; -import com.lagou.edu.pojo.Account; -import com.lagou.edu.dao.AccountDao; -import com.lagou.edu.utils.ConnectionUtils; -import com.lagou.edu.utils.DruidUtils; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -/** - * @author 应癫 - */ -@Repository(value = "accountDao") -public class JdbcAccountDaoImpl implements AccountDao { - - @Autowired - private ConnectionUtils connectionUtils; - - public void setConnectionUtils(ConnectionUtils connectionUtils) { - this.connectionUtils = connectionUtils; - } - - - public void init() { - System.out.println("初始化方法....."); - } - - public void destory() { - System.out.println("销毁方法......"); - } - - @Override - public Account queryAccountByCardNo(String cardNo) throws Exception { - //从连接池获取连接 - // Connection con = DruidUtils.getInstance().getConnection(); - Connection con = connectionUtils.getCurrentThreadConn(); - String sql = "select * from account where cardNo=?"; - PreparedStatement preparedStatement = con.prepareStatement(sql); - preparedStatement.setString(1,cardNo); - ResultSet resultSet = preparedStatement.executeQuery(); - - Account account = new Account(); - while(resultSet.next()) { - account.setCardNo(resultSet.getString("cardNo")); - account.setName(resultSet.getString("name")); - account.setMoney(resultSet.getInt("money")); - } - - resultSet.close(); - preparedStatement.close(); - //con.close(); - - return account; - } - - @Override - public int updateAccountByCardNo(Account account) throws Exception { - - // 从连接池获取连接 - // 改造为:从当前线程当中获取绑定的connection连接 - //Connection con = DruidUtils.getInstance().getConnection(); - Connection con = connectionUtils.getCurrentThreadConn(); - String sql = "update account set money=? where cardNo=?"; - PreparedStatement preparedStatement = con.prepareStatement(sql); - preparedStatement.setInt(1,account.getMoney()); - preparedStatement.setString(2,account.getCardNo()); - int i = preparedStatement.executeUpdate(); - - preparedStatement.close(); - //con.close(); - return i; - } -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/factory/AnnotationBeanFactory.java b/code/lagou-transfer/src/main/java/com/lagou/edu/factory/AnnotationBeanFactory.java deleted file mode 100755 index d04d07c138bf4bb06d35bf00b06d9871034645bf..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/factory/AnnotationBeanFactory.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.lagou.edu.factory; - -import com.alibaba.druid.util.StringUtils; -import com.lagou.edu.annotation.Autowired; -import com.lagou.edu.annotation.Repository; -import com.lagou.edu.annotation.Service; -import com.lagou.edu.annotation.Transactional; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; -import org.reflections.Reflections; - -import java.io.InputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; - -/** - * - * 工厂类,生产对象(使用反射技术) 注解方式 - */ -public class AnnotationBeanFactory { - - // IOC容器 - private static Map map = new HashMap<>(); - - // 业务逻辑类 所在包 - private static final String reposityPackage = "com.lagou.edu"; - - /** - * 任务一: - * 扫描业务逻辑所在包的 @Repository 和 @Service注解标识的类,创建其实例 并 放入map集合; - * 扫描map集合中实例字段,有@Autowired修饰则进行依赖注入,若有@Transactional修饰则注入其代理类; - */ - static { - // 扫描业务包 reposityPackage 下所有@Repository 和 @Service注解标识的类 - Reflections reflections = new Reflections(reposityPackage); - Set> repositySet = new HashSet<>(); - repositySet.addAll( reflections.getTypesAnnotatedWith(Repository.class) ); - repositySet.addAll( reflections.getTypesAnnotatedWith(Service.class) ); - - // 创建单例对象放入容器(id为 注解的value 或者 类名小写首字母) - for (Class clazz : repositySet){ - try { - // 实例创建 - Object bean = clazz.newInstance(); - - // id确定 - Repository reposityAnnotation = (Repository) clazz.getAnnotation(Repository.class); - Service serviceAnnotation = (Service) clazz.getAnnotation(Service.class); - String clazzName = clazz.getName(); - String id = getBeanId(reposityAnnotation ,serviceAnnotation , clazzName); - - map.put(id , bean); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - - // 依赖注入 - for (Map.Entry entry : map.entrySet()){ - String key = entry.getKey(); - Object value = entry.getValue(); - Class clazz = value.getClass(); - Field[] declaredFields = clazz.getDeclaredFields(); - for (Field f : declaredFields){ - if(f.isAnnotationPresent(Autowired.class)){ - // 获取容器中 字段名对应的对象 - String id = f.getName(); - Object o = map.get(id); - - f.setAccessible( true ); - try { - f.set(value , o); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - } - - // 代理对象替换 - if (clazz.isAnnotationPresent(Transactional.class)){ - ProxyFactory proxyFactory = (ProxyFactory)map.get("proxyFactory"); - Class[] interfaces = clazz.getInterfaces(); - if (interfaces != null && interfaces.length > 0){ - value = proxyFactory.getJdkProxy(value); - } else { - value = proxyFactory.getCglibProxy(value); - } - } - map.put(key , value); - } - } - - /** - * 优先取注解上的value值,若为空,则默认为 类名的首字母小写的字符串 - */ - private static String getBeanId(Repository reposityAnnotation, Service serviceAnnotation, String clazzName) { - if (reposityAnnotation != null && !StringUtils.isEmpty( reposityAnnotation.value() )){ - return reposityAnnotation.value(); - } - - if (serviceAnnotation != null && !StringUtils.isEmpty( serviceAnnotation.value() )){ - return serviceAnnotation.value(); - } - - int i = clazzName.lastIndexOf("."); - String value = clazzName.substring(i + 1, clazzName.length()); - value= toFirstOneLowerCase( value ); - return value; - } - - // 字符串首字母小写 - public static String toFirstOneLowerCase(String s){ - if(Character.isLowerCase( s.charAt( 0 ) )){ - return s; - } - - return new StringBuilder() - .append(Character.toLowerCase( s.charAt( 0 ) )) - .append(s.substring(1 , s.length())) - .toString(); - } - - // 任务二:对外提供获取实例对象的接口(根据id获取) - public static Object getBean(String id) { - return map.get(id); - } - -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/factory/BeanFactory.java b/code/lagou-transfer/src/main/java/com/lagou/edu/factory/BeanFactory.java deleted file mode 100755 index edb221cd48d4a4bccbfdd5c31d268b126a199354..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/factory/BeanFactory.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.lagou.edu.factory; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.dom4j.io.SAXReader; - -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author 应癫 - * - * 工厂类,生产对象(使用反射技术) - */ -public class BeanFactory { - - /** - * 任务一:读取解析xml,通过反射技术实例化对象并且存储待用(map集合) - * 任务二:对外提供获取实例对象的接口(根据id获取) - */ - - private static Map map = new HashMap<>(); // 存储对象 - - - static { - // 任务一:读取解析xml,通过反射技术实例化对象并且存储待用(map集合) - // 加载xml - InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml"); - // 解析xml - SAXReader saxReader = new SAXReader(); - try { - Document document = saxReader.read(resourceAsStream); - Element rootElement = document.getRootElement(); - List beanList = rootElement.selectNodes("//bean"); - for (int i = 0; i < beanList.size(); i++) { - Element element = beanList.get(i); - // 处理每个bean元素,获取到该元素的id 和 class 属性 - String id = element.attributeValue("id"); // accountDao - String clazz = element.attributeValue("class"); // com.lagou.edu.dao.impl.JdbcAccountDaoImpl - // 通过反射技术实例化对象 - Class aClass = Class.forName(clazz); - Object o = aClass.newInstance(); // 实例化之后的对象 - - // 存储到map中待用 - map.put(id,o); - - } - - // 实例化完成之后维护对象的依赖关系,检查哪些对象需要传值进入,根据它的配置,我们传入相应的值 - // 有property子元素的bean就有传值需求 - List propertyList = rootElement.selectNodes("//property"); - // 解析property,获取父元素 - for (int i = 0; i < propertyList.size(); i++) { - Element element = propertyList.get(i); // - String name = element.attributeValue("name"); - String ref = element.attributeValue("ref"); - - // 找到当前需要被处理依赖关系的bean - Element parent = element.getParent(); - - // 调用父元素对象的反射功能 - String parentId = parent.attributeValue("id"); - Object parentObject = map.get(parentId); - // 遍历父对象中的所有方法,找到"set" + name - Method[] methods = parentObject.getClass().getMethods(); - for (int j = 0; j < methods.length; j++) { - Method method = methods[j]; - if(method.getName().equalsIgnoreCase("set" + name)) { // 该方法就是 setAccountDao(AccountDao accountDao) - method.invoke(parentObject,map.get(ref)); - } - } - - // 把处理之后的parentObject重新放到map中 - map.put(parentId,parentObject); - - } - - - } catch (DocumentException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - - } - - - // 任务二:对外提供获取实例对象的接口(根据id获取) - public static Object getBean(String id) { - return map.get(id); - } - -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/factory/ProxyFactory.java b/code/lagou-transfer/src/main/java/com/lagou/edu/factory/ProxyFactory.java deleted file mode 100755 index b34e8282bacce459f5819b0ba16ed82f1dabd5a6..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/factory/ProxyFactory.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.lagou.edu.factory; - -import com.lagou.edu.annotation.Autowired; -import com.lagou.edu.annotation.Repository; -import com.lagou.edu.pojo.Account; -import com.lagou.edu.utils.TransactionManager; -import net.sf.cglib.proxy.Enhancer; -import net.sf.cglib.proxy.MethodInterceptor; -import net.sf.cglib.proxy.MethodProxy; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author 应癫 - * - * - * 代理对象工厂:生成代理对象的 - */ -@Repository -public class ProxyFactory { - - @Autowired - private TransactionManager transactionManager; - - public void setTransactionManager(TransactionManager transactionManager) { - this.transactionManager = transactionManager; - } - - /*private ProxyFactory(){ - - } - - private static ProxyFactory proxyFactory = new ProxyFactory(); - - public static ProxyFactory getInstance() { - return proxyFactory; - }*/ - - - - /** - * Jdk动态代理 - * @param obj 委托对象 - * @return 代理对象 - */ - public Object getJdkProxy(Object obj) { - - // 获取代理对象 - return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), - new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Object result = null; - - try{ - // 开启事务(关闭事务的自动提交) - transactionManager.beginTransaction(); - - result = method.invoke(obj,args); - - // 提交事务 - - transactionManager.commit(); - }catch (Exception e) { - e.printStackTrace(); - // 回滚事务 - transactionManager.rollback(); - - // 抛出异常便于上层servlet捕获 - throw e; - - } - - return result; - } - }); - - } - - - /** - * 使用cglib动态代理生成代理对象 - * @param obj 委托对象 - * @return - */ - public Object getCglibProxy(Object obj) { - return Enhancer.create(obj.getClass(), new MethodInterceptor() { - @Override - public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { - Object result = null; - try{ - // 开启事务(关闭事务的自动提交) - transactionManager.beginTransaction(); - - result = method.invoke(obj,objects); - - // 提交事务 - - transactionManager.commit(); - }catch (Exception e) { - e.printStackTrace(); - // 回滚事务 - transactionManager.rollback(); - - // 抛出异常便于上层servlet捕获 - throw e; - - } - return result; - } - }); - } -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/pojo/Account.java b/code/lagou-transfer/src/main/java/com/lagou/edu/pojo/Account.java deleted file mode 100755 index 50125a01bc08bef869a4cc5e251958137e70a080..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/pojo/Account.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.lagou.edu.pojo; - -/** - * @author 应癫 - */ -public class Account { - - private String cardNo; - private String name; - private int money; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getMoney() { - return money; - } - - public void setMoney(int money) { - this.money = money; - } - - public String getCardNo() { return cardNo; } - - public void setCardNo(String cardNo) { this.cardNo = cardNo;} - - @Override - public String toString() { - return "Account{" + - "cardNo='" + cardNo + '\'' + - ", name='" + name + '\'' + - ", money=" + money + - '}'; - } -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/pojo/Result.java b/code/lagou-transfer/src/main/java/com/lagou/edu/pojo/Result.java deleted file mode 100755 index 3e3961da2c623b4c8d29cfd5698e23f097c7ea8a..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/pojo/Result.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.lagou.edu.pojo; - -/** - * @author 应癫 - */ -public class Result { - - private String status; - private String message; - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - return "Result{" + - "status='" + status + '\'' + - ", message='" + message + '\'' + - '}'; - } -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/service/TransferService.java b/code/lagou-transfer/src/main/java/com/lagou/edu/service/TransferService.java deleted file mode 100755 index fc75bbf8621ad3997e2c0010546688974603837e..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/service/TransferService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.lagou.edu.service; - -/** - * @author 应癫 - */ -public interface TransferService { - - void transfer(String fromCardNo,String toCardNo,int money) throws Exception; -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/service/impl/TransferServiceImpl.java b/code/lagou-transfer/src/main/java/com/lagou/edu/service/impl/TransferServiceImpl.java deleted file mode 100755 index e670a3ced6161868e64479c06b9b9666395fefa9..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/service/impl/TransferServiceImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.lagou.edu.service.impl; - -import com.lagou.edu.annotation.Autowired; -import com.lagou.edu.annotation.Service; -import com.lagou.edu.dao.AccountDao; -import com.lagou.edu.pojo.Account; -import com.lagou.edu.service.TransferService; -import com.lagou.edu.utils.ConnectionUtils; -import com.lagou.edu.utils.TransactionManager; - -/** - * @author 应癫 - */ -@Service(value = "transferService") -public class TransferServiceImpl implements TransferService { - - //private AccountDao accountDao = new JdbcAccountDaoImpl(); - - // private AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao"); - - // 最佳状态 - @Autowired - private AccountDao accountDao; - - // 构造函数传值/set方法传值 - - public void setAccountDao(AccountDao accountDao) { - this.accountDao = accountDao; - } - - - - @Override - public void transfer(String fromCardNo, String toCardNo, int money) throws Exception { - - /*try{ - // 开启事务(关闭事务的自动提交) - TransactionManager.getInstance().beginTransaction();*/ - - Account from = accountDao.queryAccountByCardNo(fromCardNo); - Account to = accountDao.queryAccountByCardNo(toCardNo); - - from.setMoney(from.getMoney()-money); - to.setMoney(to.getMoney()+money); - - accountDao.updateAccountByCardNo(to); - int c = 1/0; - accountDao.updateAccountByCardNo(from); - - /* // 提交事务 - - TransactionManager.getInstance().commit(); - }catch (Exception e) { - e.printStackTrace(); - // 回滚事务 - TransactionManager.getInstance().rollback(); - - // 抛出异常便于上层servlet捕获 - throw e; - - }*/ - - - - - } -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/servlet/TransferServlet.java b/code/lagou-transfer/src/main/java/com/lagou/edu/servlet/TransferServlet.java deleted file mode 100755 index d8d45d6a96b2265933bb1f018f256dc268c50953..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/servlet/TransferServlet.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.lagou.edu.servlet; - -import com.lagou.edu.factory.AnnotationBeanFactory; -import com.lagou.edu.factory.ProxyFactory; -import com.lagou.edu.utils.JsonUtils; -import com.lagou.edu.pojo.Result; -import com.lagou.edu.service.TransferService; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @author 应癫 - */ -@WebServlet(name="transferServlet",urlPatterns = "/transferServlet") -public class TransferServlet extends HttpServlet { - - // 1. 实例化service层对象 - //private TransferService transferService = new TransferServiceImpl(); - //private TransferService transferService = (TransferService) BeanFactory.getBean("transferService"); - - // 从工厂获取委托对象(委托对象是增强了事务控制的功能) - - // 首先从BeanFactory获取到proxyFactory代理工厂的实例化对象 - private ProxyFactory proxyFactory = (ProxyFactory) AnnotationBeanFactory.getBean("proxyFactory"); - private TransferService transferService = (TransferService) proxyFactory.getJdkProxy(AnnotationBeanFactory.getBean("transferService")) ; - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - doPost(req,resp); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - // 设置请求体的字符编码 - req.setCharacterEncoding("UTF-8"); - - String fromCardNo = req.getParameter("fromCardNo"); - String toCardNo = req.getParameter("toCardNo"); - String moneyStr = req.getParameter("money"); - int money = Integer.parseInt(moneyStr); - - Result result = new Result(); - - try { - - // 2. 调用service层方法 - transferService.transfer(fromCardNo,toCardNo,money); - result.setStatus("200"); - } catch (Exception e) { - e.printStackTrace(); - result.setStatus("201"); - result.setMessage(e.toString()); - } - - // 响应 - resp.setContentType("application/json;charset=utf-8"); - resp.getWriter().print(JsonUtils.object2Json(result)); - } -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/ConnectionUtils.java b/code/lagou-transfer/src/main/java/com/lagou/edu/utils/ConnectionUtils.java deleted file mode 100755 index 1f3a762f821aa9e39d378e3c5030da6d1938e0fc..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/ConnectionUtils.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.lagou.edu.utils; - -import com.lagou.edu.annotation.Repository; - -import java.sql.Connection; -import java.sql.SQLException; - -/** - * @author 应癫 - */ -@Repository -public class ConnectionUtils { - - /*private ConnectionUtils() { - - } - - private static ConnectionUtils connectionUtils = new ConnectionUtils(); - - public static ConnectionUtils getInstance() { - return connectionUtils; - }*/ - - - private ThreadLocal threadLocal = new ThreadLocal<>(); // 存储当前线程的连接 - - /** - * 从当前线程获取连接 - */ - public Connection getCurrentThreadConn() throws SQLException { - /** - * 判断当前线程中是否已经绑定连接,如果没有绑定,需要从连接池获取一个连接绑定到当前线程 - */ - Connection connection = threadLocal.get(); - if(connection == null) { - // 从连接池拿连接并绑定到线程 - connection = DruidUtils.getInstance().getConnection(); - // 绑定到当前线程 - threadLocal.set(connection); - } - return connection; - - } -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/DruidUtils.java b/code/lagou-transfer/src/main/java/com/lagou/edu/utils/DruidUtils.java deleted file mode 100755 index f1657d93b0ca337da3925e554d29fcecb80d79b5..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/DruidUtils.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.lagou.edu.utils; - -import com.alibaba.druid.pool.DruidDataSource; - -/** - * @author 应癫 - */ -public class DruidUtils { - - private DruidUtils(){ - } - - private static DruidDataSource druidDataSource = new DruidDataSource(); - - - static { - druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); - druidDataSource.setUrl("jdbc:mysql://localhost:3306/bank"); - druidDataSource.setUsername("root"); - druidDataSource.setPassword("7"); - - } - - public static DruidDataSource getInstance() { - return druidDataSource; - } - -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/JsonUtils.java b/code/lagou-transfer/src/main/java/com/lagou/edu/utils/JsonUtils.java deleted file mode 100755 index dd20b02247328dcbb2f9b81692690c3ecedb5a92..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/JsonUtils.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.lagou.edu.utils; - -import java.util.List; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * JSON工具类(使用的是jackson实现的) - * @author 应癫 - */ -public class JsonUtils { - - private static final ObjectMapper MAPPER = new ObjectMapper(); - - /** - * 将对象转换成json字符串。 - * @param data - * @return - */ - public static String object2Json(Object data) { - try { - String string = MAPPER.writeValueAsString(data); - return string; - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 将json结果集转化为对象 - * - * @param jsonData json数据 - * @param beanType 对象中的object类型 - * @return - */ - public static T json2Pojo(String jsonData, Class beanType) { - try { - T t = MAPPER.readValue(jsonData, beanType); - return t; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 将json数据转换成pojo对象list - * @param jsonData - * @param beanType - * @return - */ - public static List json2List(String jsonData, Class beanType) { - JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); - try { - List list = MAPPER.readValue(jsonData, javaType); - return list; - } catch (Exception e) { - e.printStackTrace(); - } - - return null; - } - -} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/TransactionManager.java b/code/lagou-transfer/src/main/java/com/lagou/edu/utils/TransactionManager.java deleted file mode 100755 index 2508036facde42a15a30285d1ec35c99542f7326..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/utils/TransactionManager.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.lagou.edu.utils; - -import com.lagou.edu.annotation.Autowired; -import com.lagou.edu.annotation.Repository; - -import java.sql.SQLException; - -/** - * @author 应癫 - * - * 事务管理器类:负责手动事务的开启、提交、回滚 - */ -@Repository -public class TransactionManager { - - @Autowired - private ConnectionUtils connectionUtils; - - public void setConnectionUtils(ConnectionUtils connectionUtils) { - this.connectionUtils = connectionUtils; - } - - /*private TransactionManager(){ - - } - - private static TransactionManager transactionManager = new TransactionManager(); - - public static TransactionManager getInstance() { - return transactionManager; - }*/ - - - - // 开启手动事务控制 - public void beginTransaction() throws SQLException { - connectionUtils.getCurrentThreadConn().setAutoCommit(false); - } - - - // 提交事务 - public void commit() throws SQLException { - connectionUtils.getCurrentThreadConn().commit(); - } - - - // 回滚事务 - public void rollback() throws SQLException { - connectionUtils.getCurrentThreadConn().rollback(); - } -} diff --git a/code/lagou-transfer/src/main/resources/beans.xml b/code/lagou-transfer/src/main/resources/beans.xml deleted file mode 100755 index 6ec0912e1bcc2f071cc6d45bee1081712b8df8fe..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/resources/beans.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/code/lagou-transfer/src/main/webapp/index.html b/code/lagou-transfer/src/main/webapp/index.html deleted file mode 100755 index cfd63b0d5d1cf43e804f70d7a187fc43c1d171a8..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/webapp/index.html +++ /dev/null @@ -1,146 +0,0 @@ - - - - - 转账汇款 - - - - - - - - - - -
- - - - - - - - - - - - - - - - - -
- - - diff --git a/code/lagou-transfer/src/main/webapp/js/jquery-3.4.1.min.js b/code/lagou-transfer/src/main/webapp/js/jquery-3.4.1.min.js deleted file mode 100755 index a1c07fd803b5fc9c54f44e31123ae4fa11e134b0..0000000000000000000000000000000000000000 --- a/code/lagou-transfer/src/main/webapp/js/jquery-3.4.1.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.lagou.edu - lagou-transfer + mvc 1.0-SNAPSHOT war - lagou-transfer Maven Webapp + mvc Maven Webapp http://www.example.com @@ -19,37 +19,15 @@ 8 - - - - - org.reflections - reflections - 0.9.12 - - - junit junit 4.12 + test - - - mysql - mysql-connector-java - 8.0.19 - - - - com.alibaba - druid - 1.1.21 - - javax.servlet javax.servlet-api @@ -57,49 +35,37 @@ provided - - com.fasterxml.jackson.core - jackson-databind - 2.9.6 - - - - - dom4j - dom4j - 1.6.1 - - - - jaxen - jaxen - 1.1.6 - - - - cglib - cglib - 2.1_2 + org.apache.commons + commons-lang3 + 3.9 + + + + - + + org.apache.maven.plugins maven-compiler-plugin - 3.2 + 3.1 8 8 - UTF-8 + utf-8 + + + -parameters + - - + org.apache.tomcat.maven tomcat7-maven-plugin diff --git a/code/mvc/src/main/java/com/lagou/demo/controller/DemoController.java b/code/mvc/src/main/java/com/lagou/demo/controller/DemoController.java new file mode 100644 index 0000000000000000000000000000000000000000..bf612f2e45c1d050e963a7e489629b543134a915 --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/demo/controller/DemoController.java @@ -0,0 +1,45 @@ +package com.lagou.demo.controller; + +import com.lagou.demo.service.IDemoService; +import com.lagou.edu.mvcframework.annotations.LagouAutowired; +import com.lagou.edu.mvcframework.annotations.LagouController; +import com.lagou.edu.mvcframework.annotations.LagouRequestMapping; +import com.lagou.edu.mvcframework.annotations.Security; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@LagouController +@LagouRequestMapping("/demo") +@Security(value = "admin") +public class DemoController { + + + @LagouAutowired + private IDemoService demoService; + + + /** + * URL: /demo/query?name=lisi + * @param request + * @param response + * @param name + * @return + */ + @LagouRequestMapping("/query") + public String query(HttpServletRequest request, HttpServletResponse response,String name) { + return demoService.get(name); + } + + @LagouRequestMapping("/getOnlyByUser1") + @Security(value = "user1") + public String getOnlyByUser1(HttpServletRequest request, HttpServletResponse response,String name) { + return demoService.getOnlyByUser1(name); + } + + @LagouRequestMapping("/getOnlyByUser2") + @Security(value = "user2") + public String getOnlyByUser2(HttpServletRequest request, HttpServletResponse response,String name) { + return demoService.getOnlyByUser2(name); + } +} diff --git a/code/mvc/src/main/java/com/lagou/demo/service/IDemoService.java b/code/mvc/src/main/java/com/lagou/demo/service/IDemoService.java new file mode 100644 index 0000000000000000000000000000000000000000..cdaa480f518121e9abd303ad9640ef85dce969c9 --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/demo/service/IDemoService.java @@ -0,0 +1,10 @@ +package com.lagou.demo.service; + +public interface IDemoService { + + String get(String name); + + String getOnlyByUser1(String name); + + String getOnlyByUser2(String name); +} diff --git a/code/mvc/src/main/java/com/lagou/demo/service/impl/DemoServiceImpl.java b/code/mvc/src/main/java/com/lagou/demo/service/impl/DemoServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..45aafddb171355f87930963b5e3402113a455194 --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/demo/service/impl/DemoServiceImpl.java @@ -0,0 +1,23 @@ +package com.lagou.demo.service.impl; + +import com.lagou.demo.service.IDemoService; +import com.lagou.edu.mvcframework.annotations.LagouService; + +@LagouService("demoService") +public class DemoServiceImpl implements IDemoService { + @Override + public String get(String name) { + System.out.println("service 实现类中的name参数:" + name) ; + return name; + } + + @Override + public String getOnlyByUser1(String name) { + return get(name); + } + + @Override + public String getOnlyByUser2(String name) { + return get(name); + } +} diff --git a/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouAutowired.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouAutowired.java new file mode 100644 index 0000000000000000000000000000000000000000..8e10a01777a18a48ff0902890b884f9b07db170d --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouAutowired.java @@ -0,0 +1,10 @@ +package com.lagou.edu.mvcframework.annotations; + +import java.lang.annotation.*; + +@Documented +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface LagouAutowired { + String value() default ""; +} diff --git a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Repository.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouController.java similarity index 30% rename from code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Repository.java rename to code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouController.java index 01445a4fe3849055567904ad7eebf57510499ab2..5022b35e1e81fb3ad3a5d0e395f81c40eae6cf45 100644 --- a/code/lagou-transfer/src/main/java/com/lagou/edu/annotation/Repository.java +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouController.java @@ -1,12 +1,10 @@ -package com.lagou.edu.annotation; +package com.lagou.edu.mvcframework.annotations; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; +@Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface Repository { +public @interface LagouController { String value() default ""; } diff --git a/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouRequestMapping.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouRequestMapping.java new file mode 100644 index 0000000000000000000000000000000000000000..f075c513973f5f06b17e71b971173595e2e96eaf --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouRequestMapping.java @@ -0,0 +1,10 @@ +package com.lagou.edu.mvcframework.annotations; + +import java.lang.annotation.*; + +@Documented +@Target({ElementType.TYPE,ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface LagouRequestMapping { + String value() default ""; +} diff --git a/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouService.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouService.java new file mode 100644 index 0000000000000000000000000000000000000000..c7214fc64214bfb4043d324f89c55faa1aa6f7c1 --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/LagouService.java @@ -0,0 +1,10 @@ +package com.lagou.edu.mvcframework.annotations; + +import java.lang.annotation.*; + +@Documented +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface LagouService { + String value() default ""; +} diff --git a/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/Security.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/Security.java new file mode 100644 index 0000000000000000000000000000000000000000..32d2d7d65cacdfad90d23592ef0bf28208e4b59e --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/annotations/Security.java @@ -0,0 +1,10 @@ +package com.lagou.edu.mvcframework.annotations; + +import java.lang.annotation.*; + +@Documented +@Target(value = {ElementType.TYPE , ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Security { + String[] value(); +} diff --git a/code/mvc/src/main/java/com/lagou/edu/mvcframework/exception/SecurityException.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/exception/SecurityException.java new file mode 100644 index 0000000000000000000000000000000000000000..df0e6dc7b78dbf7a3277e0ac4cc74fc64874b9c9 --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/exception/SecurityException.java @@ -0,0 +1,31 @@ +package com.lagou.edu.mvcframework.exception; + +public class SecurityException extends Throwable { + private Integer code; + + private String msg; + + public SecurityException() { + } + + public SecurityException(Integer code, String msg) { + this.code = code; + this.msg = msg; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } +} diff --git a/code/mvc/src/main/java/com/lagou/edu/mvcframework/pojo/Handler.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/pojo/Handler.java new file mode 100644 index 0000000000000000000000000000000000000000..0b6d074d066c2543efe3b182ec230f400eb65583 --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/pojo/Handler.java @@ -0,0 +1,69 @@ +package com.lagou.edu.mvcframework.pojo; + +import javax.sound.midi.MetaEventListener; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + + +/** + * 封装handler方法相关的信息 + */ +public class Handler { + + private Object controller; // method.invoke(obj,) + + private Method method; + + private Pattern pattern; // spring中url是支持正则的 + + private Map paramIndexMapping; // 参数顺序,是为了进行参数绑定,key是参数名,value代表是第几个参数 + + private Set allowedUserSet = new HashSet<>(); + + public Set getAllowedUserSet() { + return allowedUserSet; + } + + public Handler(Object controller, Method method, Pattern pattern) { + this.controller = controller; + this.method = method; + this.pattern = pattern; + this.paramIndexMapping = new HashMap<>(); + } + + public Object getController() { + return controller; + } + + public void setController(Object controller) { + this.controller = controller; + } + + public Method getMethod() { + return method; + } + + public void setMethod(Method method) { + this.method = method; + } + + public Pattern getPattern() { + return pattern; + } + + public void setPattern(Pattern pattern) { + this.pattern = pattern; + } + + public Map getParamIndexMapping() { + return paramIndexMapping; + } + + public void setParamIndexMapping(Map paramIndexMapping) { + this.paramIndexMapping = paramIndexMapping; + } +} diff --git a/code/mvc/src/main/java/com/lagou/edu/mvcframework/servlet/LgDispatcherServlet.java b/code/mvc/src/main/java/com/lagou/edu/mvcframework/servlet/LgDispatcherServlet.java new file mode 100644 index 0000000000000000000000000000000000000000..06cf76d4c32cc4d0647ed733258b84479a571df9 --- /dev/null +++ b/code/mvc/src/main/java/com/lagou/edu/mvcframework/servlet/LgDispatcherServlet.java @@ -0,0 +1,418 @@ +package com.lagou.edu.mvcframework.servlet; + +import com.lagou.edu.mvcframework.exception.SecurityException; +import com.lagou.edu.mvcframework.annotations.*; +import com.lagou.edu.mvcframework.pojo.Handler; +import org.apache.commons.lang3.StringUtils; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class LgDispatcherServlet extends HttpServlet { + + + private Properties properties = new Properties(); + + private List classNames = new ArrayList<>(); // 缓存扫描到的类的全限定类名 + + // ioc容器 + private Map ioc = new HashMap(); + + + // handlerMapping + //private Map handlerMapping = now HashMap<>(); // 存储url和Method之间的映射关系 + private List handlerMapping = new ArrayList<>(); + + @Override + public void init(ServletConfig config) throws ServletException { + // 1 加载配置文件 springmvc.properties + String contextConfigLocation = config.getInitParameter("contextConfigLocation"); + doLoadConfig(contextConfigLocation); + + // 2 扫描相关的类,扫描注解 + doScan(properties.getProperty("scanPackage")); + + + // 3 初始化bean对象(实现ioc容器,基于注解) + doInstance(); + + // 4 实现依赖注入 + doAutoWired(); + + // 5 构造一个HandlerMapping处理器映射器,将配置好的url和Method建立映射关系 + initHandlerMapping(); + + System.out.println("lagou mvc 初始化完成...."); + + // 等待请求进入,处理请求 + } + + /* + 构造一个HandlerMapping处理器映射器 + 最关键的环节 + 目的:将url和method建立关联 + */ + private void initHandlerMapping() { + if(ioc.isEmpty()) {return;} + + for(Map.Entry entry: ioc.entrySet()) { + // 获取ioc中当前遍历的对象的class类型 + Class aClass = entry.getValue().getClass(); + + + if(!aClass.isAnnotationPresent(LagouController.class)) {continue;} + + + String baseUrl = ""; + if(aClass.isAnnotationPresent(LagouRequestMapping.class)) { + LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class); + baseUrl = annotation.value(); // 等同于/demo + } + + String[] controllerAllowedUsers = new String[]{}; + if(aClass.isAnnotationPresent(Security.class)) { + Security annotation = aClass.getAnnotation(Security.class); + controllerAllowedUsers = annotation.value(); + } + + // 获取方法 + Method[] methods = aClass.getMethods(); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + // 方法没有标识LagouRequestMapping,就不处理 + if(!method.isAnnotationPresent(LagouRequestMapping.class)) {continue;} + + // 如果标识,就处理 + LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class); + String methodUrl = annotation.value(); // /query + String url = baseUrl + methodUrl; // 计算出来的url /demo/query + + // 把method所有信息及url封装为一个Handler + Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url)); + + + // 计算方法的参数位置信息 // query(HttpServletRequest request, HttpServletResponse response,String name) + Parameter[] parameters = method.getParameters(); + for (int j = 0; j < parameters.length; j++) { + Parameter parameter = parameters[j]; + + if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) { + // 如果是request和response对象,那么参数名称写HttpServletRequest和HttpServletResponse + handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j); + }else{ + handler.getParamIndexMapping().put(parameter.getName(),j); // + } + + } + + addUser(handler.getAllowedUserSet() , controllerAllowedUsers); + if(method.isAnnotationPresent(Security.class)) { + Security annotationSecurity = method.getAnnotation(Security.class); + addUser(handler.getAllowedUserSet() , annotationSecurity.value()); + } + + // 建立url和method之间的映射关系(map缓存起来) + handlerMapping.add(handler); + + } + + + } + + } + + private void addSecurityUser(Set allowedUserSet, String[] controllerAllowedUsers, String[] value) { + if (controllerAllowedUsers.length > 0){ + addUser(allowedUserSet , controllerAllowedUsers); + } + + if (value.length > 0){ + addUser(allowedUserSet , value); + } + } + + private void addUser(Set allowedUserSet, String[] controllerAllowedUsers) { + if (controllerAllowedUsers == null || controllerAllowedUsers.length <1){ + return; + } + for (String user : controllerAllowedUsers){ + allowedUserSet.add( user ); + } + } + + // 实现依赖注入 + private void doAutoWired() { + if(ioc.isEmpty()) {return;} + + // 有对象,再进行依赖注入处理 + + // 遍历ioc中所有对象,查看对象中的字段,是否有@LagouAutowired注解,如果有需要维护依赖注入关系 + for(Map.Entry entry: ioc.entrySet()) { + // 获取bean对象中的字段信息 + Field[] declaredFields = entry.getValue().getClass().getDeclaredFields(); + // 遍历判断处理 + for (int i = 0; i < declaredFields.length; i++) { + Field declaredField = declaredFields[i]; // @LagouAutowired private IDemoService demoService; + if(!declaredField.isAnnotationPresent(LagouAutowired.class)) { + continue; + } + + + // 有该注解 + LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class); + String beanName = annotation.value(); // 需要注入的bean的id + if("".equals(beanName.trim())) { + // 没有配置具体的bean id,那就需要根据当前字段类型注入(接口注入) IDemoService + beanName = declaredField.getType().getName(); + } + + // 开启赋值 + declaredField.setAccessible(true); + + try { + declaredField.set(entry.getValue(),ioc.get(beanName)); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + } + + + } + + + + + } + + + // ioc容器 + // 基于classNames缓存的类的全限定类名,以及反射技术,完成对象创建和管理 + private void doInstance() { + + if(classNames.size() == 0) return; + + try{ + + for (int i = 0; i < classNames.size(); i++) { + String className = classNames.get(i); // com.lagou.demo.controller.DemoController + + // 反射 + Class aClass = Class.forName(className); + // 区分controller,区分service' + if(aClass.isAnnotationPresent(LagouController.class)) { + // controller的id此处不做过多处理,不取value了,就拿类的首字母小写作为id,保存到ioc中 + String simpleName = aClass.getSimpleName();// DemoController + String lowerFirstSimpleName = lowerFirst(simpleName); // demoController + Object o = aClass.newInstance(); + ioc.put(lowerFirstSimpleName,o); + }else if(aClass.isAnnotationPresent(LagouService.class)) { + LagouService annotation = aClass.getAnnotation(LagouService.class); + //获取注解value值 + String beanName = annotation.value(); + + // 如果指定了id,就以指定的为准 + if(!"".equals(beanName.trim())) { + ioc.put(beanName,aClass.newInstance()); + }else{ + // 如果没有指定,就以类名首字母小写 + beanName = lowerFirst(aClass.getSimpleName()); + ioc.put(beanName,aClass.newInstance()); + } + + + // service层往往是有接口的,面向接口开发,此时再以接口名为id,放入一份对象到ioc中,便于后期根据接口类型注入 + Class[] interfaces = aClass.getInterfaces(); + for (int j = 0; j < interfaces.length; j++) { + Class anInterface = interfaces[j]; + // 以接口的全限定类名作为id放入 + ioc.put(anInterface.getName(),aClass.newInstance()); + } + }else{ + continue; + } + + } + }catch (Exception e) { + e.printStackTrace(); + } + + + + + + + } + + + // 首字母小写方法 + public String lowerFirst(String str) { + char[] chars = str.toCharArray(); + if('A' <= chars[0] && chars[0] <= 'Z') { + chars[0] += 32; + } + return String.valueOf(chars); + } + + + + + // 扫描类 + // scanPackage: com.lagou.demo package----> 磁盘上的文件夹(File) com/lagou/demo + private void doScan(String scanPackage) { + String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/"); + File pack = new File(scanPackagePath); + + File[] files = pack.listFiles(); + + for(File file: files) { + if(file.isDirectory()) { // 子package + // 递归 + doScan(scanPackage + "." + file.getName()); // com.lagou.demo.controller + }else if(file.getName().endsWith(".class")) { + String className = scanPackage + "." + file.getName().replaceAll(".class", ""); + classNames.add(className); + } + + } + + + } + + // 加载配置文件 + private void doLoadConfig(String contextConfigLocation) { + + InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation); + + try { + properties.load(resourceAsStream); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + doPost(req,resp); + } + + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + // 处理请求:根据url,找到对应的Method方法,进行调用 + // 获取uri +// String requestURI = req.getRequestURI(); +// Method method = handlerMapping.get(requestURI);// 获取到一个反射的方法 + // 反射调用,需要传入对象,需要传入参数,此处无法完成调用,没有把对象缓存起来,也没有参数!!!!改造initHandlerMapping(); +// method.invoke() // + + + // 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list)) + Handler handler = getHandler(req); + + try { + ensureSecurity(handler , req); + } catch (SecurityException e) { + resp.getWriter().write(e.getMsg()); + return; + } + + if(handler == null) { + resp.getWriter().write("404 not found"); + return; + } + + // 参数绑定 + // 获取所有参数类型数组,这个数组的长度就是我们最后要传入的args数组的长度 + Class[] parameterTypes = handler.getMethod().getParameterTypes(); + + + // 根据上述数组长度创建一个新的数组(参数数组,是要传入反射调用的) + Object[] paraValues = new Object[parameterTypes.length]; + + // 以下就是为了向参数数组中塞值,而且还得保证参数的顺序和方法中形参顺序一致 + + Map parameterMap = req.getParameterMap(); + + // 遍历request中所有参数 (填充除了request,response之外的参数) + for(Map.Entry param: parameterMap.entrySet()) { + // name=1&name=2 name [1,2] + String value = StringUtils.join(param.getValue(), ","); // 如同 1,2 + + // 如果参数和方法中的参数匹配上了,填充数据 + if(!handler.getParamIndexMapping().containsKey(param.getKey())) {continue;} + + // 方法形参确实有该参数,找到它的索引位置,对应的把参数值放入paraValues + Integer index = handler.getParamIndexMapping().get(param.getKey());//name在第 2 个位置 + + paraValues[index] = value; // 把前台传递过来的参数值填充到对应的位置去 + + } + + + int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0 + paraValues[requestIndex] = req; + + + int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1 + paraValues[responseIndex] = resp; + + + + + // 最终调用handler的method属性 + try { + Object res = handler.getMethod().invoke(handler.getController(), paraValues); + resp.getWriter().write(res.toString()); + + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + + } + + private boolean ensureSecurity(Handler handler, HttpServletRequest req) throws SecurityException{ + String[] usernames = req.getParameterValues("username"); + if (usernames!=null && usernames.length > 0 && handler.getAllowedUserSet().contains( usernames[0] )){ + return true; + }else{ + throw new SecurityException(999 , "no ahth!"); + } + + } + + private Handler getHandler(HttpServletRequest req) { + if(handlerMapping.isEmpty()){return null;} + + String url = req.getRequestURI(); + + for(Handler handler: handlerMapping) { + Matcher matcher = handler.getPattern().matcher(url); + if(!matcher.matches()){continue;} + return handler; + } + + return null; + + } + + +} diff --git a/code/mvc/src/main/resources/springmvc.properties b/code/mvc/src/main/resources/springmvc.properties new file mode 100644 index 0000000000000000000000000000000000000000..28e2b4697da4d45c40b38bf90f9bfc6bbb05dfd9 --- /dev/null +++ b/code/mvc/src/main/resources/springmvc.properties @@ -0,0 +1 @@ +scanPackage=com.lagou.demo \ No newline at end of file diff --git a/code/lagou-transfer/src/main/webapp/WEB-INF/web.xml b/code/mvc/src/main/webapp/WEB-INF/web.xml old mode 100755 new mode 100644 similarity index 33% rename from code/lagou-transfer/src/main/webapp/WEB-INF/web.xml rename to code/mvc/src/main/webapp/WEB-INF/web.xml index 9f88c1f9632445500e3b3688fe477b860f77d8f2..b3de15423589bc64cd655b20ef49d2a5f038f774 --- a/code/lagou-transfer/src/main/webapp/WEB-INF/web.xml +++ b/code/mvc/src/main/webapp/WEB-INF/web.xml @@ -4,4 +4,19 @@ Archetype Created Web Application + + + + lgoumvc + com.lagou.edu.mvcframework.servlet.LgDispatcherServlet + + contextConfigLocation + springmvc.properties + + + + + lgoumvc + /* + diff --git a/code/mvc/src/main/webapp/index.jsp b/code/mvc/src/main/webapp/index.jsp new file mode 100644 index 0000000000000000000000000000000000000000..c38169bb958579c635a5c09ee2f379cc5956c0c2 --- /dev/null +++ b/code/mvc/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + diff --git "a/\344\275\234\344\270\232\351\252\214\350\257\201\350\265\204\346\226\231/my\344\275\234\344\270\232\350\256\262\350\247\243.pdf" "b/\344\275\234\344\270\232\351\252\214\350\257\201\350\265\204\346\226\231/my\344\275\234\344\270\232\350\256\262\350\247\243.pdf" index 38bbaa8d1bb6385c25499557d683c096547e7b20..548c0945a1de17e642ae45712b06337e8f8dc5a2 100644 Binary files "a/\344\275\234\344\270\232\351\252\214\350\257\201\350\265\204\346\226\231/my\344\275\234\344\270\232\350\256\262\350\247\243.pdf" and "b/\344\275\234\344\270\232\351\252\214\350\257\201\350\265\204\346\226\231/my\344\275\234\344\270\232\350\256\262\350\247\243.pdf" differ diff --git "a/\345\220\254\350\257\276\347\254\224\350\256\260/1 \350\207\252\345\256\232\344\271\211IOC & AOP\346\241\206\346\236\266.pdf" "b/\345\220\254\350\257\276\347\254\224\350\256\260/1 \350\207\252\345\256\232\344\271\211IOC & AOP\346\241\206\346\236\266.pdf" deleted file mode 100644 index cb20810f405cf7a7d429b42e0d346deedd065086..0000000000000000000000000000000000000000 Binary files "a/\345\220\254\350\257\276\347\254\224\350\256\260/1 \350\207\252\345\256\232\344\271\211IOC & AOP\346\241\206\346\236\266.pdf" and /dev/null differ diff --git "a/\345\220\254\350\257\276\347\254\224\350\256\260/2 Spring IOC\351\253\230\347\272\247 \345\272\224\347\224\250\344\270\216\346\272\220\347\240\201\350\247\243\346\236\220.pdf" "b/\345\220\254\350\257\276\347\254\224\350\256\260/1. \345\237\272\347\241\200\345\233\236\351\241\276.pdf" similarity index 32% rename from "\345\220\254\350\257\276\347\254\224\350\256\260/2 Spring IOC\351\253\230\347\272\247 \345\272\224\347\224\250\344\270\216\346\272\220\347\240\201\350\247\243\346\236\220.pdf" rename to "\345\220\254\350\257\276\347\254\224\350\256\260/1. \345\237\272\347\241\200\345\233\236\351\241\276.pdf" index 89f5a5888f3e74ec42c9b51533962af42ec01732..cae6aee6da25894bec2ff3604537b579e2dd6a97 100644 Binary files "a/\345\220\254\350\257\276\347\254\224\350\256\260/2 Spring IOC\351\253\230\347\272\247 \345\272\224\347\224\250\344\270\216\346\272\220\347\240\201\350\247\243\346\236\220.pdf" and "b/\345\220\254\350\257\276\347\254\224\350\256\260/1. \345\237\272\347\241\200\345\233\236\351\241\276.pdf" differ diff --git "a/\345\220\254\350\257\276\347\254\224\350\256\260/2. \350\207\252\345\256\232\344\271\211MVC\346\241\206\346\236\266.pdf" "b/\345\220\254\350\257\276\347\254\224\350\256\260/2. \350\207\252\345\256\232\344\271\211MVC\346\241\206\346\236\266.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..9b40052e58da190ea65367c9961304daa8828ea2 Binary files /dev/null and "b/\345\220\254\350\257\276\347\254\224\350\256\260/2. \350\207\252\345\256\232\344\271\211MVC\346\241\206\346\236\266.pdf" differ diff --git "a/\345\220\254\350\257\276\347\254\224\350\256\260/\351\242\204\344\271\240.pdf" "b/\345\220\254\350\257\276\347\254\224\350\256\260/\351\242\204\344\271\240.pdf" new file mode 100644 index 0000000000000000000000000000000000000000..7075863b7c336bfa0753b1f796070bcf019a81a4 Binary files /dev/null and "b/\345\220\254\350\257\276\347\254\224\350\256\260/\351\242\204\344\271\240.pdf" differ diff --git "a/\345\220\254\350\257\276\347\254\224\350\256\260/\351\242\204\344\271\240\350\265\204\346\226\231.pdf" "b/\345\220\254\350\257\276\347\254\224\350\256\260/\351\242\204\344\271\240\350\265\204\346\226\231.pdf" deleted file mode 100644 index 531976962b4e29cd5506f5487b123f159cff0416..0000000000000000000000000000000000000000 Binary files "a/\345\220\254\350\257\276\347\254\224\350\256\260/\351\242\204\344\271\240\350\265\204\346\226\231.pdf" and /dev/null differ