上一篇介紹到要寫mvc的所用的核心技術,這一篇咱們就開始真正的開始寫mvc,其實就是把昨天寫過的代碼進行一些組裝就能夠了。html
咱們用eclipse新建一個web項目。而後web.xml以下java
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>kis</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置action攔截器 --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>com.keepitsimple.core.DispatcherServlet</servlet-class> <init-param> <param-name>scan_package</param-name> <param-value>com.mvc</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- 配置action攔截器 --> </web-app>
在web.xml裏咱們配置一個servlet攔截器。攔截全部的action請求。而後init-param裏配置一下action所在路徑,咱們要進行自動掃描。這個功能就相似與spring的自動掃描裝備功能。用的好像也是咱們用到的寫法。git
而後就開始寫這個servletweb
在這個servlet裏咱們實現doGet,doPost方法,還有init方法。spring
init方法呢,主要做用就是裝配掃描beantomcat
代碼片斷以下:安全
@Override public void init(final ServletConfig config) throws ServletException { // TODO Auto-generated method stub super.init(config); String scan_package = config.getInitParameter("scan_package"); DispatcherServletHelper.init(scan_package); }
能夠看到,這裏這裏經過config.getinitParameter("scan_packge")讀取web.xml中的initparam。也就是掃描包的路徑。mvc
在各類跳轉過程當中,咱們須要一個java bean來裝一些咱們須要的參數。app
package com.keepitsimple.core; public class ActionContext{ private String URL; //調用的url,也就是actionname private String methodName; //調用的方法名稱 private Class<?> cla; //調用方法的類名 private Object action;//類的實例 private String result;//返回結果 private Class<?>[] paramsType;// 調用方法的參數類型 private String[] actionParamsName;//調用的方法參數的名稱 //getter and setter
而後咱們定義一下自定義註解,讓方法只掃描咱們註解了的類。eclipse
package com.keepitsimple.core; 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.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented() public @interface ActionAnnotate { String ActionName() default ""; String Result() default ""; }
而後咱們調用Helper的init方法。init方法主要就是把上面這個類填充。初始化裝載全部的action。
package com.keepitsimple.core; import java.io.File; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.Modifier; import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; public final class DispatcherServletHelper { public static Map<String, ServletListenerBean> urls = null; // public DispatcherServletHelper() // { // getURLs(); // } public static void init(String scan_package) { if (null == scan_package || scan_package.length() <= 0) System.out.println("正在掃描classpath...."); urls = new HashMap<String, ServletListenerBean>(); String result = DispatcherServletHelper.class.getResource("/").toString().replace("file:/", "").replace("%20", ""); try { assembleBean(result, result.replace("/", "\\"), scan_package); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 掃描該路徑下 全部的class文件 then 裝配bean * * @param realPath * @param root * 真實路徑 E:\\GitHome\\kis\\build\\classes\\ * @param scan_package * 掃描的包 * @return * @throws Exception * @throws */ public static String assembleBean(String realPath, String root, String scan_package) throws Exception { File file = new File(realPath); if (file.isDirectory()) { for (File f : file.listFiles()) { if (f.isDirectory()) { assembleBean(f.getAbsolutePath(), root, scan_package); } else { String classPath = f.getAbsolutePath().replace("\\", "."); int len = classPath.length(); if (len > 6 && classPath.endsWith(".class")) { if(null!=scan_package&&scan_package.length()>0&&classPath.indexOf("classes."+scan_package)>=0){ classPath = classPath.substring(8+classPath.indexOf("classes."+scan_package)); }else{ continue; } String className = classPath.substring(0, classPath.length() - 6); Class<?> clazz = Class.forName(className); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(com.keepitsimple.core.ActionAnnotate.class)) { com.keepitsimple.core.ActionAnnotate actionAnno = method.getAnnotation(com.keepitsimple.core.ActionAnnotate.class); if (urls.containsKey(actionAnno.ActionName())) { throw new RuntimeException("重複路徑" + clazz + ":" + actionAnno.ActionName()); } else { ActionContext bean = new ActionContext (); bean.setCla(clazz); bean.setMethodName(method.getName()); bean.setURL(actionAnno.ActionName()); bean.setResult(actionAnno.Result()); bean.setAction(clazz.newInstance()); bean.setParamsType(method.getParameterTypes()); bean.setActionParamsName(Utils.getParamNames(clazz, method.getName())); urls.put(actionAnno.ActionName(), bean); } } } } } } } return ""; } }
上面這段代碼就是整個的helper類。經過掃描文件而後裝配bean。
如今這個mvc的初始化就完成了。這個裏面有很多問題。但願你們可以發現,而且嘗試改一下。(注1)
doGet方法咱們就直接調用doPost來處理
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }
doPost方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String path = request.getServletPath();// 獲取請求action /addUser.action path = path.substring(1);// addUser.action if (DispatcherServletHelper.urls.containsKey(path)) { ActionContext bean = DispatcherServletHelper.urls.get(path); Class<?> cla = bean.getCla(); Object actionObject = bean.getAction(); if (bean.getParamsType() != null) { BeanUtils beanUtils = new BeanUtils(); Object[] params = beanUtils.getMethodParam(request, bean.getParamsType(),bean.getActionParamsName());//這裏就是封裝jsp傳過來的參數 System.out.println("action方法名:" + bean.getMethodName()); System.out.println("方法參數屬性:" + bean.getParamsType()); System.out.println("action實體類:" + actionObject); System.out.println("action方法參數:" + params); try { cla.getMethod(bean.getMethodName(), bean.getParamsType()).invoke(actionObject, params);//反射調用action方法 } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (bean.getResult() != null) { request.getRequestDispatcher(bean.getResult()).forward(request, response); } } }
下面咱們看看怎麼來封裝方法所須要的參數。
package com.keepitsimple.core; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; public class BeanUtils<T> { private static Map<Class<?>, Class<?>> classMap = new HashMap<Class<?>, Class<?>>(); static { classMap.put(int.class, Integer.class); classMap.put(short.class, Short.class); classMap.put(long.class, Long.class); classMap.put(float.class, Float.class); classMap.put(double.class, Double.class); classMap.put(char.class, Character.class); classMap.put(boolean.class, Boolean.class); classMap.put(byte.class, Byte.class); classMap.put(Integer.class, Integer.class); classMap.put(Short.class, Short.class); classMap.put(Long.class, Long.class); classMap.put(Float.class, Float.class); classMap.put(Double.class, Double.class); classMap.put(Character.class, Character.class); classMap.put(Boolean.class, Boolean.class); classMap.put(Byte.class, Byte.class); classMap.put(String.class, String.class); } public Object[] getMethodParam(HttpServletRequest request, Class<?>[] paramsType, String[] actionParamsName) { Object[] params = new Object[actionParamsName.length]; for (int i = 0; i < actionParamsName.length; i++) { Map<String, String[]> requestMap = request.getParameterMap(); Iterator<Entry<String, String[]>> it = requestMap.entrySet().iterator(); try { Object object = paramsType[i].newInstance(); while (it.hasNext()) { System.out.println(i); if (isBasicType(paramsType[i])) { Entry<String, String[]> entry = it.next(); String value = ""; for (String s : entry.getValue()) { value += s; } if (entry.getKey().equals(actionParamsName[i])) { params[i] = basicType(paramsType[i], value); } } else { Field[] fields = paramsType[i].getDeclaredFields(); Entry<String, String[]> entry = it.next(); String paramName; String value = ""; for (String s : entry.getValue()) { value += s; } if (entry.getKey().indexOf(".") > 0 && entry.getKey().split("\\.")[0].equals(actionParamsName[i])) { for (Field field : fields) { if (field.getName().equals(entry.getKey().split("\\.")[1])) { paramName = entry.getKey().split("\\.")[1]; String methodName = "set" + toFirstLetterUpperCase(paramName); paramsType[i].getMethod(methodName, field.getType()).invoke(object, value); } } params[i] = object; } } } } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return params; } private boolean isBasicType(Class clazz) { if (clazz.equals(int.class) || clazz.equals(Integer.class)) { return true; } else if (clazz.equals(short.class) || clazz.equals(Short.class)) { return true; } else if (clazz.equals(long.class) || clazz.equals(Long.class)) { return true; } else if (clazz.equals(float.class) || clazz.equals(Float.class)) { return true; } else if (clazz.equals(double.class) || clazz.equals(Double.class)) { return true; } else if (clazz.equals(char.class) || clazz.equals(Character.class)) { return true; } else if (clazz.equals(boolean.class) || clazz.equals(Boolean.class)) { return true; } else if (clazz.equals(byte.class) || clazz.equals(Byte.class)) { return true; } else if (clazz.equals(String.class)) { return true; } else { return false; } } /** * 基礎數據綁定 * @param class1 * @param value * @return */ private Object basicType(Class<?> class1, String value) { if (isBasicType(class1)) { Class<?> newClass = classMap.get(class1); if (newClass.equals(Integer.class)) { return Integer.parseInt(value); } else if (newClass.equals(Short.class)) { return Short.parseShort(value); } else if (newClass.equals(Long.class)) { return Long.parseLong(value); } else if (newClass.equals(Float.class)) { return Float.parseFloat(value); } else if (newClass.equals(Double.class)) { return Double.parseDouble(value); } else if (newClass.equals(Character.class)) { return value.toCharArray()[0]; } else if (newClass.equals(Boolean.class)) { return Boolean.parseBoolean(value); } else if (newClass.equals(Byte.class)) { return Byte.parseByte(value); } else { return value; } } else if (class1.equals(java.util.Date.class)) { try { if (value.indexOf(":") == -1) { return new SimpleDateFormat("yyyy-MM-dd").parse(value); } else return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value); } catch (Exception e) { e.printStackTrace(); return null; } } else { return class1.cast(value); } } /** * 轉換String的第一個字母 * @param s * @return */ public String toFirstLetterUpperCase(String s) { if (s.length() == 1) { return s.toUpperCase(); } else if (s == null || s.length() == 0) { return ""; } else { return s.substring(0, 1).toUpperCase() + s.substring(1); } } }
上面這段基本都是昨天的代碼。利用反射來進行封裝,這裏面基礎數據只作了簡單的封裝。還不是很完整,
關於getMethodParam()方法,大家能夠藉助於commons-beanutils.jar包來實現,用這個方法比較簡單。
可是這裏爲了增強你們對反射的理解跟應用,我就採用了反射來作。
剛纔個人注1那裏,主要的問題是,這個ActionContext是不是線程安全,是否還能改裝?還有一個問題是 若是 一個action要有多種跳轉結果怎麼辦?
至此,咱們就實現了一個最簡單的mvc功能。如今把他添加到tomcat裏。就能夠運行本身的mvc了。
這mvc系列到這就結束了,剩下的就是一些細節的處理。
這個mvc我也在寫 也在一直完善。
上面的代碼,你們能夠在個人git裏check出來。而且實現了action多個跳轉結果。但願你們本身想一想怎麼實現。本身去實現,若是不能實如今check out個人代碼。
https://git.oschina.net/sum/kis.git
關於git工具。你們能夠看個人上一篇博文,裏面有介紹GIT工具。
這裏面你們有不明白的能夠給我留言,必定會積極回覆。
謝謝你們
The End