一:梳理SpringMVC的設計思路
本文只實現本身的@Controller、@RequestMapping、@RequestParam註解起做用,其他SpringMVC功能讀者能夠嘗試本身實現。 html
一、讀取配置
SpringMVC本質上是一個Servlet,這個 Servlet 繼承自 HttpServlet。FrameworkServlet負責初始化SpringMVC的容器,並將Spring容器設置爲父容器。由於本文只是實現SpringMVC,對於Spring容器不作過多講解。java
爲了讀取web.xml中的配置,咱們用到ServletConfig這個類,它表明當前Servlet在web.xml中的配置信息。經過web.xml中加載咱們本身寫的MyDispatcherServlet和讀取配置文件。web
二、初始化階段
-
加載配置文件app
-
掃描用戶配置包下面全部的類框架
-
拿到掃描到的類,經過反射機制,實例化。而且放到ioc容器中(Map的鍵值對 beanName-bean) beanName默認是首字母小寫jsp
-
初始化HandlerMapping,這裏其實就是把url和method對應起來放在一個k-v的Map中,在運行階段取出ide
三、運行階段
每一次請求將會調用doGet或doPost方法,因此統一運行階段都放在doDispatch方法裏處理,它會根據url請求去HandlerMapping中匹配到對應的Method,而後利用反射機制調用Controller中的url對應的方法,並獲得結果返回。按順序包括如下功能:測試
-
異常的攔截this
-
獲取請求傳入的參數並處理參數url
-
經過初始化好的handlerMapping中拿出url對應的方法名,反射調用
2、實現本身的SpringMVC框架
工程文件及目錄:
用到javax.servlet.jar
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>web01</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>MySpringMVC</servlet-name> <servlet-class>com.gdut.servlet.MyDispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>application.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MySpringMVC</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
application.properties文件中只是配置要掃描的包到SpringMVC容器中。application.properties文件內容爲:
建立本身的Controller註解,它只能標註在類上面:
package com.gdut.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 MyController { /** * 表示給controller註冊別名 * @return */ String value() default ""; }
RequestMapping註解,能夠在類和方法上:
package com.gdut.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,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyRequestMapping { /** * 表示訪問該方法的url * @return */ String value() default ""; }
RequestParam註解,只能註解在參數上
package com.gdut.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.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyRequestParam { /** * 表示參數的別名,必填 * @return */ String value(); }
而後建立MyDispatcherServlet這個類,去繼承HttpServlet,重寫init方法、doGet、doPost方法,以及加上咱們第二步分析時要實現的功能:
package com.gdut.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gdut.annotation.MyController; import com.gdut.annotation.MyRequestMapping; public class MyDispatcherServlet extends HttpServlet { private Properties properties = new Properties(); private List<String> classNames = new ArrayList<>(); private Map<String, Object> ioc = new HashMap<>(); private Map<String, Method> handlerMapping = new HashMap<>(); private Map<String, Object> controllerMap = new HashMap<>(); @Override public void init(ServletConfig config) throws ServletException { // 1.加載配置文件 doLoadConfig(config.getInitParameter("contextConfigLocation")); // 2.初始化全部相關聯的類,掃描用戶設定的包下面全部的類 doScanner(properties.getProperty("scanPackage")); // 3.拿到掃描到的類,經過反射機制,實例化,而且放到ioc容器中(k-v beanName-bean) beanName默認是首字母小寫 doInstance(); // 4.初始化HandlerMapping(將url和method對應上) initHandlerMapping(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // 處理請求 doDispatch(req, resp); } catch (Exception e) { resp.getWriter().write("500!! Server Exception"); } } private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception { if (handlerMapping.isEmpty()) { return; } String url = req.getRequestURI(); String contextPath = req.getContextPath(); url = url.replace(contextPath, "").replaceAll("/+", "/"); if (!this.handlerMapping.containsKey(url)) { resp.getWriter().write("404 NOT FOUND!"); return; } Method method = this.handlerMapping.get(url); // 獲取方法的參數列表 Class<?>[] parameterTypes = method.getParameterTypes(); // 獲取請求的參數 Map<String, String[]> parameterMap = req.getParameterMap(); // 保存參數值 Object[] paramValues = new Object[parameterTypes.length]; // 方法的參數列表 for (int i = 0; i < parameterTypes.length; i++) { // 根據參數名稱,作某些處理 String requestParam = parameterTypes[i].getSimpleName(); if (requestParam.equals("HttpServletRequest")) { // 參數類型已明確,這邊強轉類型 paramValues[i] = req; continue; } if (requestParam.equals("HttpServletResponse")) { paramValues[i] = resp; continue; } if (requestParam.equals("String")) { for (Entry<String, String[]> param : parameterMap.entrySet()) { String value = Arrays.toString(param.getValue()) .replaceAll("\\[|\\]", "").replaceAll(",\\s", ","); paramValues[i] = value; } } } // 利用反射機制來調用 try { method.invoke(this.controllerMap.get(url), paramValues);// 第一個參數是method所對應的實例 // 在ioc容器中 } catch (Exception e) { e.printStackTrace(); } } private void doLoadConfig(String location) { // 把web.xml中的contextConfigLocation對應value值的文件加載到流裏面 InputStream resourceAsStream = this.getClass().getClassLoader() .getResourceAsStream(location); // 用Properties文件加載文件裏的內容 try { properties.load(resourceAsStream); } catch (IOException e) { e.printStackTrace(); } finally { if (resourceAsStream != null) { try { resourceAsStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void doScanner(String packageName) { // 把全部的.替換成/ URL url = this.getClass().getClassLoader() .getResource("/" + packageName.replaceAll("\\.", "/")); File dir = new File(url.getFile()); for (File file : dir.listFiles()) { if (file.isDirectory()) { // 遞歸讀取包 doScanner(packageName + "." + file.getName()); } else { String className = packageName + "." + file.getName().replace(".class", ""); classNames.add(className); } } } private void doInstance() { if (classNames.isEmpty()) { return; } for (String className : classNames) { try { Class<?> clazz = Class.forName(className); if (clazz.isAnnotationPresent(MyController.class)) { ioc.put(toLowerFirstWord(clazz.getSimpleName()), clazz.newInstance()); } } catch (Exception e) { e.printStackTrace(); } } } private void initHandlerMapping() { if (ioc.isEmpty()) { return; } try { for (Entry<String, Object> entry : ioc.entrySet()) { Class<? extends Object> clazz = entry.getValue().getClass(); if (!clazz.isAnnotationPresent(MyController.class)) { continue; } // 拼url時,是controller頭的url拼上方法上的url String baseUrl = ""; if (clazz.isAnnotationPresent(MyRequestMapping.class)) { MyRequestMapping annotation = clazz .getAnnotation(MyRequestMapping.class); baseUrl = annotation.value(); } Method[] methods = clazz.getMethods(); for (Method method : methods) { if (!method.isAnnotationPresent(MyRequestMapping.class)) { continue; } MyRequestMapping annotation = method .getAnnotation(MyRequestMapping.class); String url = annotation.value(); url = (baseUrl + "/" + url).replaceAll("/+", "/"); handlerMapping.put(url, method); controllerMap.put(url, clazz.newInstance()); System.out.println(url + "," + method); } } } catch (Exception e) { e.printStackTrace(); } } /** * 把字符串的首字母小寫 * * @param name * @return */ private String toLowerFirstWord(String name) { char[] charArray = name.toCharArray(); charArray[0] += 32; return String.valueOf(charArray); } }
這裏咱們就開發完了本身的SpringMVC,如今咱們測試一下:
package com.gdut.core; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gdut.annotation.MyController; import com.gdut.annotation.MyRequestMapping; import com.gdut.annotation.MyRequestParam; @MyController @MyRequestMapping("/test") public class TestController { @MyRequestMapping("/doTest") public void test1(HttpServletRequest request, HttpServletResponse response, @MyRequestParam("param") String param){ System.out.println(param); try { response.getWriter().write( "doTest method success! param:"+param); } catch (IOException e) { e.printStackTrace(); } } @MyRequestMapping("/doTest2") public void test2(HttpServletRequest request, HttpServletResponse response){ try { response.getWriter().println("doTest2 method success!"); } catch (IOException e) { e.printStackTrace(); } } }
訪問http://localhost:8080/web01/test/doTest?param=liugh以下:
訪問一個不存在的試試:
轉自:https://www.cnblogs.com/java1024/p/8556519.html