纯手写SpringMVC框架,用注解实现springmvc过程

1、第一步,首先搭建如下架构,其中,annotation中放置自己编写的注解,主要包括service controller qualifier RequestMapping


第二步:完成对应的annotation:

  1. package com.chaoyue.annotation;  
  2. import java.lang.annotation.Documented;  
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * Controller注解 
  10.  * @author 超越 
  11.  * @Date 2016年11月29日,上午10:37:30 
  12.  * @motto 人在一起叫聚会,心在一起叫团队 
  13.  * @Version 1.0 
  14.  */  
  15. @Target({ ElementType.TYPE })  
  16. @Retention(RetentionPolicy.RUNTIME)  
  17. @Documented  
  18. public @interface Controller {  
  19.     String value() default "";  
  20. }  
  1. package com.chaoyue.annotation;  
  2. import java.lang.annotation.Documented;  
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * Quatifier注解 
  10.  * @author 超越 
  11.  * @Date 2016年11月29日,上午10:47:52 
  12.  * @motto 人在一起叫聚会,心在一起叫团队 
  13.  * @Version 1.0 
  14.  */  
  15. @Target({ ElementType.FIELD }) // 代表注解的注解  
  16. @Retention(RetentionPolicy.RUNTIME)  
  17. @Documented  
  18. public @interface Quatifier {  
  19.     String value() default "";  
  20. }  
  1. package com.chaoyue.annotation;  
  2. import java.lang.annotation.Documented;  
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * RequestMapping注解 
  10.  * @author 超越 
  11.  * @Date 2016年11月29日,上午10:39:32 
  12.  * @motto 人在一起叫聚会,心在一起叫团队 
  13.  * @Version 1.0 
  14.  */  
  15. @Target({ ElementType.METHOD }) // 在方法上的注解  
  16. @Retention(RetentionPolicy.RUNTIME)  
  17. @Documented  
  18. public @interface RequestMapping {  
  19.     String value() default "";  
  20. }  
  1. package com.chaoyue.annotation;  
  2. import java.lang.annotation.Documented;  
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * 注解Service 
  10.  * @author 超越 
  11.  * @Date 2016年11月29日,上午10:49:47 
  12.  * @motto 人在一起叫聚会,心在一起叫团队 
  13.  * @Version 1.0 
  14.  */  
  15. @Target({ ElementType.TYPE })  
  16. @Retention(RetentionPolicy.RUNTIME)  
  17. @Documented  
  18. public @interface Service {  
  19.     String value() default "";  
  20. }  
2、第二步:编写对应的servlet类,记得勾选init()方法,用来进行相应的实例化和注解反转控制。

   ① 进行包扫描,就是初始化的时候先将整个项目中的包进行扫描,扫描各个文件分别存起来。

scanPackage("com.chaoyue");//自己的项目,测试用的 所以 扫描包函数的地址写死了

   存在List<String> packageNames=new ArrayList<String>();其中都是这样:com.chaoyue.annotation.Controller.classcom.chaoyue.annotation.Quatifier.class, com.chaoyue.annotation.RequestMapping.class,有.class后缀。

  ②过滤和实例化 :由于已经将所有的文件都存在了packageNames中了,那么我们必须将对应的Controller实例化才可以进行相应函数调用,然后其中的所有文件并不一定都是对应的controller文件,所以要进行相应的过滤和处理

   filterAndInstance();

    过滤后的结果保存在:  Map<String,Object> instanceMap=new HashMap<String,Object>();

   其中 String是注解的value, Object是所对应类的实例 

  ③建立一个映射关系(地址映射,不同的地址映射到不同的方法):  

  handerMap();

  结果: Map<String,Object> handerMap=new HashMap<String,Object>();

  实例:

  ④ 反转控制,根据注解,把service中的注入到controller中的service;

  void ioc()

  1. package com.chaoyue.servlet;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.lang.reflect.Field;  
  6. import java.lang.reflect.InvocationTargetException;  
  7. import java.lang.reflect.Method;  
  8. import java.net.URL;  
  9. import java.util.ArrayList;  
  10. import java.util.HashMap;  
  11. import java.util.List;  
  12. import java.util.Map;  
  13.   
  14. import javax.servlet.ServletConfig;  
  15. import javax.servlet.ServletException;  
  16. import javax.servlet.annotation.WebServlet;  
  17. import javax.servlet.http.HttpServlet;  
  18. import javax.servlet.http.HttpServletRequest;  
  19. import javax.servlet.http.HttpServletResponse;  
  20.   
  21. import com.chaoyue.annotation.Controller;  
  22. import com.chaoyue.annotation.Quatifier;  
  23. import com.chaoyue.annotation.RequestMapping;  
  24. import com.chaoyue.annotation.Service;  
  25. import com.chaoyue.controller.SpringmvcController;  
  26.   
  27. @WebServlet("/DispatcherServlet")  
  28. public class DispatcherServlet extends HttpServlet {  
  29.     private static final long serialVersionUID = 1L;  
  30.     List<String> packageNames = new ArrayList<String>();  
  31.     // 所有类的实例,key是注解的value,value是所有类的实例  
  32.     Map<String, Object> instanceMap = new HashMap<String, Object>();  
  33.     Map<String, Object> handerMap = new HashMap<String, Object>();  
  34.     public DispatcherServlet() {  
  35.         super();  
  36.     }  
  37.   
  38.     public void init(ServletConfig config) throws ServletException {  
  39.         // 包扫描,获取包中的文件  
  40.         scanPackage("com.chaoyue");  
  41.         try {  
  42.             filterAndInstance();  
  43.         } catch (Exception e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.         // 建立映射关系  
  47.         handerMap();  
  48.         // 实现注入  
  49.         ioc();  
  50.     }  
  51.   
  52.     private void filterAndInstance() throws Exception {  
  53.         if (packageNames.size() <= 0) {  
  54.             return;  
  55.         }  
  56.         for (String className : packageNames) {  
  57.             Class<?> cName = Class.forName(className.replace(".class""").trim());  
  58.             if (cName.isAnnotationPresent(Controller.class)) {  
  59.                 Object instance = cName.newInstance();  
  60.                 Controller controller = (Controller) cName.getAnnotation(Controller.class);  
  61.                 String key = controller.value();  
  62.                 instanceMap.put(key, instance);  
  63.             } else if (cName.isAnnotationPresent(Service.class)) {  
  64.                 Object instance = cName.newInstance();  
  65.                 Service service = (Service) cName.getAnnotation(Service.class);  
  66.                 String key = service.value();  
  67.                 instanceMap.put(key, instance);  
  68.             } else {  
  69.                 continue;  
  70.             }  
  71.         }  
  72.     }  
  73.   
  74.     private void ioc() {  
  75.         if (instanceMap.isEmpty())  
  76.             return;  
  77.         for (Map.Entry<String, Object> entry : instanceMap.entrySet()) {  
  78.             // 拿到里面的所有属性  
  79.             Field fields[] = entry.getValue().getClass().getDeclaredFields();  
  80.             for (Field field : fields) {  
  81.                 field.setAccessible(true);// 可访问私有属性  
  82.                 if (field.isAnnotationPresent(Quatifier.class));  
  83.                 Quatifier quatifier = field.getAnnotation(Quatifier.class);  
  84.                 String value = quatifier.value();  
  85.                 field.setAccessible(true);  
  86.                 try {  
  87.                     field.set(entry.getValue(), instanceMap.get(value));  
  88.                 } catch (IllegalArgumentException e) {  
  89.                     e.printStackTrace();  
  90.                 } catch (IllegalAccessException e) {  
  91.                     e.printStackTrace();  
  92.                 }  
  93.             }  
  94.         }  
  95.     }  
  96.   
  97.     /** 
  98.      * 扫描包下的所有文件 
  99.      *  
  100.      * @param Package 
  101.      */  
  102.     private void scanPackage(String Package) {  
  103.         URL url = this.getClass().getClassLoader().getResource("/" + replaceTo(Package));// 将所有的.转义获取对应的路径  
  104.         String pathFile = url.getFile();  
  105.         File file = new File(pathFile);  
  106.         String fileList[] = file.list();  
  107.         for (String path : fileList) {  
  108.             File eachFile = new File(pathFile + path);  
  109.             if (eachFile.isDirectory()) {  
  110.                 scanPackage(Package + eachFile.getName());  
  111.             } else {  
  112.                 packageNames.add(Package + "." + eachFile.getName());  
  113.             }  
  114.         }  
  115.     }  
  116.   
  117.     /** 
  118.      * 建立映射关系 
  119.      */  
  120.     private void handerMap() {  
  121.         if (instanceMap.size() <= 0)  
  122.             return;  
  123.         for (Map.Entry<String, Object> entry : instanceMap.entrySet()) {  
  124.             if (entry.getValue().getClass().isAnnotationPresent(Controller.class)) {  
  125.                 Controller controller = (Controller) entry.getValue().getClass().getAnnotation(Controller.class);  
  126.                 String ctvalue = controller.value();  
  127.                 Method[] methods = entry.getValue().getClass().getMethods();  
  128.                 for (Method method : methods) {  
  129.                     if (method.isAnnotationPresent(RequestMapping.class)) {  
  130.                         RequestMapping rm = (RequestMapping) method.getAnnotation(RequestMapping.class);  
  131.                         String rmvalue = rm.value();  
  132.                         handerMap.put("/" + ctvalue + "/" + rmvalue, method);  
  133.                     } else {  
  134.                         continue;  
  135.                     }  
  136.                 }  
  137.             } else {  
  138.                 continue;  
  139.             }  
  140.   
  141.         }  
  142.     }  
  143.   
  144.     private String replaceTo(String path) {  
  145.         return path.replaceAll("\\.""/");  
  146.     }  
  147.   
  148.     @Override  
  149.     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
  150.         this.doGet(req, resp);  
  151.     }  
  152.   
  153.     @Override  
  154.     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
  155.         String url = req.getRequestURI();  
  156.         String context = req.getContextPath();  
  157.         String path = url.replace(context, "");  
  158.         Method method = (Method) handerMap.get(path);  
  159.         SpringmvcController controller = (SpringmvcController) instanceMap.get(path.split("/")[1]);  
  160.         try {  
  161.             method.invoke(controller, new Object[] { req, resp, null });  
  162.         } catch (IllegalAccessException e) {  
  163.             e.printStackTrace();  
  164.         } catch (IllegalArgumentException e) {  
  165.             e.printStackTrace();  
  166.         } catch (InvocationTargetException e) {  
  167.             e.printStackTrace();  
  168.         }  
  169.     }  
  170.   
  171. }  
  1. package com.chaoyue.controller;  
  2. import javax.servlet.http.HttpServletRequest;  
  3. import javax.servlet.http.HttpServletResponse;  
  4. import com.chaoyue.annotation.Controller;  
  5. import com.chaoyue.annotation.Quatifier;  
  6. import com.chaoyue.annotation.RequestMapping;  
  7. import com.chaoyue.service.impl.MyService;  
  8. import com.chaoyue.service.impl.SpringmvcServiceImpl;  
  9.   
  10. @Controller("chaoyue")  
  11. public class SpringmvcController {  
  12.     @Quatifier("MyServiceImpl")  
  13.     MyService myService;  
  14.     @Quatifier("SpringmvcServiceImpl")  
  15.     SpringmvcServiceImpl smService;  
  16.   
  17.     @RequestMapping("insert")  
  18.     public String insert(HttpServletRequest request, HttpServletResponse response, String param) {  
  19.         myService.insert(null);  
  20.         smService.insert(null);  
  21.         return null;  
  22.     }  
  23.   
  24.     @RequestMapping("delete")  
  25.     public String delete(HttpServletRequest request, HttpServletResponse response, String param) {  
  26.         myService.delete(null);  
  27.         smService.delete(null);  
  28.         return null;  
  29.     }  
  30.   
  31.     @RequestMapping("update")  
  32.     public String update(HttpServletRequest request, HttpServletResponse response, String param) {  
  33.         myService.update(null);  
  34.         smService.update(null);  
  35.         return null;  
  36.     }  
  37.   
  38.     @RequestMapping("select")  
  39.     public String select(HttpServletRequest request, HttpServletResponse response, String param) {  
  40.         myService.select(null);  
  41.         smService.select(null);  
  42.         return null;  
  43.     }  
  44. }  

  1. package com.chaoyue.service.impl;  
  2. import java.util.Map;  
  3.   
  4. public interface MyService {  
  5.     int insert(Map map);  
  6.   
  7.     int delete(Map map);  
  8.   
  9.     int update(Map map);  
  10.   
  11.     int select(Map map);  
  12. }  
  1. package com.chaoyue.service.impl;  
  2. import java.util.Map;  
  3. import com.chaoyue.annotation.Service;  
  4.   
  5. @Service("MyServiceImpl")  
  6. public class MyServiceImpl implements MyService {  
  7.     @Override  
  8.     public int insert(Map map) {  
  9.         System.out.println("MyServiceImpl:" + "insert");  
  10.         return 0;  
  11.     }  
  12.   
  13.     @Override  
  14.     public int delete(Map map) {  
  15.         System.out.println("MyServiceImpl:" + "delete");  
  16.         return 0;  
  17.     }  
  18.   
  19.     @Override  
  20.     public int update(Map map) {  
  21.         System.out.println("MyServiceImpl:" + "update");  
  22.         return 0;  
  23.     }  
  24.   
  25.     @Override  
  26.     public int select(Map map) {  
  27.         System.out.println("MyServiceImpl:" + "select");  
  28.         return 0;  
  29.     }  
  30. }  
  1. package com.chaoyue.service.impl;  
  2. import java.util.Map;  
  3.   
  4. public interface SpringmvcService {  
  5.     int insert(Map map);  
  6.   
  7.     int delete(Map map);  
  8.   
  9.     int update(Map map);  
  10.   
  11.     int select(Map map);  
  12. }  
  1. package com.chaoyue.service.impl;  
  2. import java.util.Map;  
  3.   
  4. public class SpringmvcServiceImpl implements SpringmvcService {  
  5.   
  6.     @Override  
  7.     public int insert(Map map) {  
  8.         System.out.println("SpringmvcServiceImpl:" + "insert");  
  9.         return 0;  
  10.     }  
  11.   
  12.     @Override  
  13.     public int delete(Map map) {  
  14.         System.out.println("SpringmvcServiceImpl:" + "delete");  
  15.         return 0;  
  16.     }  
  17.   
  18.     @Override  
  19.     public int update(Map map) {  
  20.         System.out.println("SpringmvcServiceImpl:" + "update");  
  21.         return 0;  
  22.     }  
  23.   
  24.     @Override  
  25.     public int select(Map map) {  
  26.         System.out.println("SpringmvcServiceImpl:" + "select");  
  27.         return 0;  
  28.     }  
  29.   

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值