純手寫SpringMVC架構,用註解實現springmvc過程(動腦學院Jack老師課後自己練習的體會)
標籤:
1、第一步,首先搭建如下架構,其中,annotation中放置自己編寫的註解,主要包括service controller qualifier RequestMapping
第二步:完成對應的annotation:
package com.cn.annotation; import java.lang.annotation.Documented; 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)//這是代表執行的時候啟動 @Documented public @interface Controller { String value() default ""; }
1 package com.cn.annotation; 2 3 import java.lang.annotation.Documented; 4 import java.lang.annotation.ElementType; 5 import java.lang.annotation.Retention; 6 import java.lang.annotation.RetentionPolicy; 7 import java.lang.annotation.Target; 8 9 @Target({ElementType.METHOD})//在方法上的註解 10 @Retention(RetentionPolicy.RUNTIME)View Code11 @Documented 12 public @interface RequestMapping { 13 String value() default ""; 14 }
1 package com.cn.annotation; 2 3 import java.lang.annotation.Documented; 4 import java.lang.annotation.ElementType; 5 import java.lang.annotation.Retention; 6 import java.lang.annotation.RetentionPolicy;View Code7 import java.lang.annotation.Target; 8 9 @Target({ElementType.FIELD})//代表註解的註解 10 @Retention(RetentionPolicy.RUNTIME) 11 @Documented 12 public @interface Quatifier { 13 String value() default ""; 14 }
package com.cn.annotation; import java.lang.annotation.Documented; 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) @Documented public @interface Service { String value() default ""; }View Code
以後我們需要什麼註解都可以自己建立, 直接右鍵建立一個註解就可以了。這裡是模仿springmvc,所以jack老師就任性的建立了幾個原來springmvc幾個相同的註解
2、第二步:編寫對應的servlet類,記得勾選init()方法,用來進行相應的例項化和註解反轉控制。
① 進行包掃描,就是初始化的時候先將整個專案中的包進行掃描,掃描各個檔案分別存起來。
scanPackage("com.cn");//自己的專案,測試用的 所以 掃描包函式的地址寫死了
存在 List<String> packageNames=new ArrayList<String>();其中都是這樣:com.cn.annotation.Controller.class ,com.cn.annotation.Quatifier.class, com.cn.annotation.RequestMapping.class,有.class字尾。
②過濾和例項化 :由於已經將所有的檔案都存在了packageNames中了,那麼我們必須將對應的Controller例項化才可以進行相應函式呼叫,然後其中的所有檔案並不一定都是對應的controller檔案,所以要進行相應的過濾和處理
filterAndInstance();
過濾後的結果儲存在: Map<String,Object> instanceMap=new HashMap<String,Object>();
其中 String是註解的value, Object是所對應類的例項
比如:我專案中DEBUG結果instanceMap{[email protected], [email protected], [email protected]1d90a3}
③建立一個對映關係(地址對映,不同的地址對映到不同的方法): handerMap();
結果: Map<String,Object> handerMap=new HashMap<String,Object>();
例項:{/dongnao/select=public java.lang.String com.cn.controller.SpringmvcController.select(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,java.lang.String), /dongnao/delet=public java.lang.String com.cn.controller.SpringmvcController.delet(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,java.lang.String), /dongnao/insert=public java.lang.String com.cn.controller.SpringmvcController.insert(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,java.lang.String), /dongnao/update=public java.lang.String com.cn.controller.SpringmvcController.update(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse,java.lang.String)}
④ 反轉控制,
根據註解,把service中的注入到controller中的service;
void ioc()
1 package com.cn.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.cn.annotation.Controller; 22 import com.cn.annotation.Quatifier; 23 import com.cn.annotation.RequestMapping; 24 import com.cn.annotation.Service; 25 import com.cn.controller.SpringmvcController; 26 27 28 /** 29 * Servlet implementation class DispatcherServlet 30 */ 31 @WebServlet("/DispatcherServlet") 32 public class DispatcherServlet extends HttpServlet { 33 private static final long serialVersionUID = 1L; 34 List<String> packageNames=new ArrayList<String>(); 35 //所有類的例項 key是註解的value, value是所有類的例項 36 Map<String,Object> instanceMap=new HashMap<String,Object>(); 37 38 Map<String,Object> handerMap=new HashMap<String,Object>(); 39 /** 40 * @see HttpServlet#HttpServlet() 41 */ 42 public DispatcherServlet() { 43 super(); 44 } 45 46 /** 47 * @see Servlet#init(ServletConfig) 48 */ 49 public void init(ServletConfig config) throws ServletException { 50 //包掃描,獲取包中的檔案 51 scanPackage("com.cn"); 52 53 try { 54 filterAndInstance(); 55 } catch (Exception e) { 56 e.printStackTrace(); 57 } 58 //建立一個對映關係 59 handerMap(); 60 61 ioc();//實現注入 62 } 63 private void scanPackage(String basePackage){ 64 URL url=this.getClass().getClassLoader().getResource("/"+replaceTo(basePackage));//將所有.轉義獲取對應的路徑 65 66 String pathfile=url.getFile(); 67 File file=new File(pathfile); 68 69 String[] files=file.list(); 70 for (String path : files) { 71 File eachFile= new File(pathfile+path);//有點問題 72 if(eachFile.isDirectory()){ 73 scanPackage(basePackage+"."+eachFile.getName()); 74 }else{ 75 76 packageNames.add(basePackage+"."+eachFile.getName()); 77 } 78 79 } 80 81 } 82 private String replaceTo(String path){ 83 return path.replaceAll("\\.","/"); 84 } 85 public void handerMap(){ 86 if(instanceMap.size()<=0) 87 return; 88 for(Map.Entry<String, Object> entry:instanceMap.entrySet()){ 89 if(entry.getValue().getClass().isAnnotationPresent(Controller.class)){ 90 Controller controller=(Controller)entry.getValue().getClass().getAnnotation(Controller.class); 91 String ctvalue= controller.value(); 92 Method[] methods=entry.getValue().getClass().getMethods(); 93 for(Method method:methods){ 94 if(method.isAnnotationPresent(RequestMapping.class)){ 95 RequestMapping rm= (RequestMapping)method.getAnnotation(RequestMapping.class); 96 String rmvalue=rm.value(); 97 handerMap.put("/"+ctvalue+"/"+rmvalue,method); 98 }else{ 99 continue; 100 } 101 } 102 }else{ 103 continue; 104 } 105 106 } 107 } 108 public void ioc(){ 109 if(instanceMap.isEmpty())return; 110 111 for(Map.Entry<String, Object> entry:instanceMap.entrySet()){ 112 Field[] fields= entry.getValue().getClass().getDeclaredFields();//拿到類裡面的屬性 113 for (Field field : fields) { 114 field.setAccessible(true); 115 if(field.isAnnotationPresent(Quatifier.class)){ 116 Quatifier qf=(Quatifier)field.getAnnotation(Quatifier.class); 117 String value= qf.value(); 118 119 field.setAccessible(true); 120 try { 121 field.set(entry.getValue(), instanceMap.get(value)); 122 } catch (IllegalArgumentException e) { 123 e.printStackTrace(); 124 } catch (IllegalAccessException e) { 125 e.printStackTrace(); 126 } 127 } 128 } 129 } 130 131 } 132 public void filterAndInstance() throws Exception{ 133 if(packageNames.size()<=0){ 134 return; 135 } 136 for (String classname : packageNames) { 137 Class ccName=Class.forName(classname.replace(".class","")); 138 if(ccName.isAnnotationPresent(Controller.class)){ 139 Object instance= ccName.newInstance(); 140 Controller an= (Controller) ccName.getAnnotation(Controller.class); 141 String key=an.value(); 142 instanceMap.put(key,instance); 143 }else if(ccName.isAnnotationPresent(Service.class)){ 144 Object instance= ccName.newInstance(); 145 Service an= (Service) ccName.getAnnotation(Service.class); 146 String key=an.value(); 147 instanceMap.put(key,instance); 148 }else{ 149 continue; 150 } 151 } 152 } 153 /** 154 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 155 */ 156 protected void doGet(HttpServletRequest request, 157 HttpServletResponse response) throws ServletException, IOException { 158 this.doPost(request, response); 159 } 160 161 /** 162 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 163 */ 164 protected void doPost(HttpServletRequest request, 165 HttpServletResponse response) throws ServletException, IOException { 166 String url= request.getRequestURI(); 167 String context=request.getContextPath(); 168 String path=url.replace(context,""); 169 Method method =(Method) handerMap.get(path); 170 SpringmvcController controller=(SpringmvcController) instanceMap.get(path.split("/")[1]); 171 try { 172 method.invoke(controller, new Object[]{request,response,null}); 173 } catch (IllegalAccessException e) { 174 e.printStackTrace(); 175 } catch (IllegalArgumentException e) { 176 e.printStackTrace(); 177 } catch (InvocationTargetException e) { 178 e.printStackTrace(); 179 } 180 } 181 182 }View Code
第三步:
controller中的程式碼:
package com.cn.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.cn.annotation.Controller; import com.cn.annotation.Quatifier; import com.cn.annotation.RequestMapping; import com.cn.service.impl.MyService; import com.cn.service.impl.SpringmvcService; @Controller("dongnao") public class SpringmvcController { @Quatifier("MyServiceImpl") MyService myservice; @Quatifier("SpringmvcServiceImpl") SpringmvcService smservice; @RequestMapping("insert") public String insert(HttpServletRequest request, HttpServletResponse response,String param){ System.out.println(request.getRequestURI()+"insert"); myservice.insert(null); smservice.insert(null); return null; } @RequestMapping("delet") public String delet(HttpServletRequest request, HttpServletResponse response,String param){ myservice.delet(null); smservice.delet(null); return null; } @RequestMapping("select") public String select(HttpServletRequest request, HttpServletResponse response,String param){ myservice.select(null); smservice.select(null); return null; } @RequestMapping("update") public String update(HttpServletRequest request, HttpServletResponse response,String param){ myservice.update(null); smservice.update(null); return null; } }
package com.cn.service.impl; import java.util.Map; import com.cn.annotation.Service; public interface SpringmvcService { int insert(Map map); int delet(Map map); int update(Map map); int select(Map map); }
package com.cn.service.impl; import java.util.Map; import com.cn.annotation.Service; @Service("MyServiceImpl") public class MyServiceImpl implements MyService { public int insert(Map map) { System.out.println("MyServiceImpl:"+"insert"); return 0; } public int delet(Map map) { System.out.println("MyServiceImpl:"+"delet"); return 0; } public int update(Map map) { System.out.println("MyServiceImpl:"+"update"); return 0; } public int select(Map map) { System.out.println("MyServiceImpl:"+"select"); return 0; } }
package com.cn.service.impl; import java.util.Map; import com.cn.annotation.Service; public interface SpringmvcService { int insert(Map map); int delet(Map map); int update(Map map); int select(Map map); }
package com.cn.service.impl; import java.util.Map; import com.cn.annotation.Service; @Service("SpringmvcServiceImpl") public class SpringmvcServiceImpl implements SpringmvcService { public int insert(Map map) { System.out.println("SpringmvcServiceImpl:"+"insert"); return 0; } public int delet(Map map) { System.out.println("SpringmvcServiceImpl:"+"delet"); return 0; } public int update(Map map) { System.out.println("SpringmvcServiceImpl:"+"update"); return 0; } public int select(Map map) { System.out.println("SpringmvcServiceImpl:"+"select"); return 0; } }
標籤:
相關推薦
純手寫SpringMVC架構,用註解實現springmvc過程(動腦學院Jack老師課後自己練習的體會)
標籤: 1、第一步,首先搭建如下架構,其中,annotation中放置自己編寫的註解,主要包括service controller qualifier RequestMapping 第二步:完成對應的annotation: package com.cn.annotation; import java.
純手寫SpringMVC框架,用註解實現springmvc過程
開發十年,就只剩下這套架構體系了! >>>
jmeter手寫腳本,使用正則獲取cookie(禁用cookies管理器)
coo inf 手動 全局 其他 去掉 bugfree 因此 頭信息 註:這裏以bugfree為例 1.bugfree登錄時會有重定向,這會導致每個URL都會有。因此要手動獲取cookie的時候,需要去掉重定向勾選 正則獲取動態PHPsession 獲取到值後,放到信
手把手教你用R實現標記化(附程式碼、學習資料、語料庫)
作者:Rachael Tatman翻譯:樑傅淇本文長度為1600字,建議閱讀4分鐘標記化是自然語
純手寫SpringBoot框架之註解方式啟動SpringMVC容器
使用Java語言建立Tomcat容器,並且通過Tomcat執行Servlet,接下來,將會使用Java語言在SpringBoot建
vue10行代碼實現上拉翻頁加載更多數據,純手寫js實現下拉刷新上拉翻頁不引用任何第三方插件
each ray 如果 部分 list 插件 下拉 ast 頁面數據 vue10行代碼實現上拉翻頁加載更多數據,純手寫js實現下拉刷新上拉翻頁不引用任何第三方插件/庫 一提到移動端的下拉刷新上拉翻頁,你可能就會想到iScroll插件,沒錯iScroll是一個高性能,資源占用
純手寫SpringMVC到SpringBoot框架專案實戰
引言 Spring Boot其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。 通過這種方式,springboot是一個快速整合第三方框架的,簡化了xml的配置,專案中再也不包含web.xml檔案了
高手過招「效能優化/純手寫SpringMVC框架/MySql優化/微服務」
效能優化那些絕招,一般人我不告訴他 1,支付寶介面的介面如何正確呼叫; 2,從併發程式設計角度來提高系統性能; 3,系統響應的速度縮短N倍的祕密; 4,從Futuretask類原始碼分析到手寫; 5,快速提升Web專案吞吐量; 300行精華程式碼:純手寫SpringMVC框
基於註解方式純手寫spring-ioc
1.定義註解 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface ExtService { } 2.工具類 https://blog.csdn.net/qq_419882
攜程系統架構師帶你手寫spring mvc,解讀spring核心原始碼!
講師簡介: James老師 系統架構師、專案經理 十餘年Java經驗,曾就職於攜程、人人網等一線網際網路公司,專注於java領域,精通軟體架構設計,對於高併發、高效能服務有深刻的見解, 在服務化基礎架構和微服務技術有大量的建設和設計經驗。 課程內容: 1.為什麼讀Spr
數值分析--線性方程組解的演算法(6種)(附演算法百度雲連結,純手寫原創)
先上乾貨百度雲(純手寫,純HTML,可直接開啟),如下: 注:參考書籍《數值分析》北京航空航天大學出版社 一、順序GUASS消去法 點進去如下,先輸入要解的N階矩陣: 比如,我們輸入3: 出現下方的矩陣框,為(N+1)*N的增廣矩陣,輸入待計算的矩陣,然
純手寫利用poi讀取xls檔案,並通過JDBC存入MySQL資料庫
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019
純手寫Spring IoC容器之自定義註解實現
由於我在CSDN編輯器上寫這篇文章的時候,在貼上圖片上來的時候總是出現了卡頓,所以就另外寫了一個word文件裡面了,具體的實現過程請下載,裡面有文件、原始碼、資料庫sql檔案 連結:https://pan.baidu.com/s/1La2FIhlVKSt7JLh393V8I
Mybatis深入原始碼分析之基於裝飾模式純手寫一級,二級,三級快取
寫在前面:設計模式源於生活,而又高於生活! 什麼是裝飾者模式 在不改變原有物件的基礎上附加功能,相比生成子類更靈活。
太刺激了,面試官讓我手寫跳錶,而我用兩種實現方式吊打了TA!
# 前言 > 本文收錄於專輯:[http://dwz.win/HjK](http://dwz.win/HjK),點選解鎖更多資料結構與演算法的知識。 你好,我是彤哥。 上一節,我們一起學習了關於跳錶的理論知識,相信通過上一節的學習,你一定可以給面試官完完整整地講清楚跳錶的來龍去脈,甚至能夠邊講邊畫
手寫一個webpack,看看AST怎麼用
本文開始我會圍繞`webpack`和`babel`寫一系列的工程化文章,這兩個工具我雖然天天用,但是對他們的原理理解的其實不是很深入,寫這些文章的過程其實也是我深入學習的過程。由於`webpack`和`babel`的體系太大,知識點眾多,不可能一篇文章囊括所有知識點,目前我的計劃是從簡單入手,先實現一個最簡單
簡易-五星評分-jQuery純手寫
開始 round size dcl cas blog ren func fin 超級簡單的評分功能,分為四個步驟輕松搞定: 第一步: 引入jquery文件;這裏我用百度CDN的jquery: <script src="http://apps.bdimg.com/
css3純手寫loading效果
-s 1.3 utf AC keyframes title sca osi inf <!DOCTYPE html> <html> <head> <meta charset="UTF-8">
大學生簡單網頁div+css網頁純手寫代碼制作html靜態頁面切圖排版
靜態頁面 靜態頁 watermark 簡單 ima 大學生 ges 51cto mar 了解下下+2425691680 大學生簡單網頁div+css網頁純手寫代碼制作html靜態頁面切圖排版