1. 本文主要是利用少量代碼編寫出spring,springmvc的核心實現原理,僅供參考。實際與spring內置實現還有一定的差距。希望以此文幫助大家了解spring實現的一些思想,謝謝。
2. 涉及功能,IOC,DI,HandleMapping。
3. 邏輯線,從web.xml入手>>>>加載配置>>>> 掃描包路徑>>>>實例化對象保存到ioc>>>>>Autowired注入>>>>handleMapping初始化。
4. 開擼
<?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/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>xiong web application</display-name>
<servlet>
<servlet-name>xiongmvc</servlet-name>
<servlet-class>org.xiong.v1.mvcframework.servlet2.XiongDispatcherServlet2</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>application.properties</param-value>
<!-- 這里為了方便,直接用的application.properties作為配置文件,簡化了xml解析的邏輯-->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>xiongmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
<!-- web.xml -->
scanPackage=org.xiong.v1
#application.properties
package org.xiong.v1.mvcframework.servlet2;
import org.xiong.v1.mvcframework.annotation.*;
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.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
/**
* 升級版,不適用map保存url與method之間的關聯關系,使用List<HandlerMaping>存儲
*/
public class XiongDispatcherServlet2 extends HttpServlet {
private Properties contextConfig = new Properties();
/**
* 存儲所有掃描出來的類
*/
private List<String> classNames = new ArrayList<String>();
/**
* 模擬IOC容器
*/
private Map<String, Object> ioc = new HashMap<String, Object>();
/**
* 保存controller中requestmapping和method之間的對應關系
*/
private List<HandlerMapping> handlerMappings = new ArrayList<HandlerMapping>();
@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 {
//委派模式,分發
try {
doDispatcher(req, resp);
} catch (Exception e) {
e.printStackTrace();
resp.getWriter().write("500 Internal Server Exception :" + Arrays.toString(e.getStackTrace()));
}
}
/**
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
private void doDispatcher(HttpServletRequest req, HttpServletResponse resp) throws Exception {
HandlerMapping handlerMapping = HandlerMapping.getHandler(req, handlerMappings);
//handleMapping中找到url對應的method, 如果沒有就404
if (handlerMapping == null) {
resp.getWriter().write("404 Not Found");
return;
}
Method method = handlerMapping.getMethod();
//獲取請求參數, 這個方法獲取的參數是不可修改的,只能讀取,安全規范WebLogic,Tomcat,Resin,JBoss等服務器均實現了此規范
Map<String, String[]> params = req.getParameterMap();
//獲取方法的形參列表
Class<?>[] parameterTypes = method.getParameterTypes();
//保存賦值參數的位置
Object[] paramValues = new Object[parameterTypes.length];
//按照參數的位置動態賦值
for (Map.Entry<String, String[]> param : params.entrySet()){
String value = Arrays.toString(param.getValue())
.replaceAll("\\[|\\]", "")
.replaceAll(",\\s", ",");
if(handlerMapping.getParamIndexMapping().containsKey(param.getKey())) {
int index = handlerMapping.getParamIndexMapping().get(param.getKey());
//參數類型可能是其他類型,這里需要進行相關轉換,目前demo中只對integer double進行轉換(多種類型轉換,避免多個if else可以使用策略模式)
paramValues[index] = covert(parameterTypes[index],value);
}
}
//設置方法中request,response的值
int reqIndex = handlerMapping.getParamIndexMapping().get(HttpServletRequest.class.getName());
paramValues[reqIndex] = req;
int respIndex = handlerMapping.getParamIndexMapping().get(HttpServletResponse.class.getName());
paramValues[respIndex] = resp;
//利用反射執行方法
method.invoke(handlerMapping.getController(), paramValues);
}
/**
* 將string類型轉換成其他類型的參數
* 這里暫時只寫demo中的integer和double兩種
* @param parameterType
* @param value
* @return
*/
private Object covert(Class<?> parameterType, String value) {
if (parameterType == Integer.class) {
return Integer.valueOf(value);
} else if (parameterType == Double.class) {
return Double.valueOf(value);
}
return value;
}
@Override
public void init(ServletConfig config) throws ServletException {
//1. 加載配置文件
doLoadConfig(config.getInitParameter("contextConfigLocation"));
//2. 掃描相關類
doScanner(contextConfig.getProperty("scanPackage"));
//3. 初始化類實例,放入到IOC容器
doInstance();
//4. 依賴注入
doAutowired();
//5. 初始化HandlerMapping
initHandlerMapping();
//完成
}
/**
* 初始化XiongRequestMapping url與method之間的關系
*/
private void initHandlerMapping() {
if (ioc.isEmpty()) {
return;
}
//找被XiongController修飾的類,找到XiongRequestMapping修飾的方法
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
Class clazz = entry.getValue().getClass();
if (!clazz.isAnnotationPresent(XiongController.class)) {
continue;
}
String baseUrl = "";
//獲取XiongController上被XiongRequestMapping修飾的值
if (clazz.isAnnotationPresent(XiongRequestMapping.class)) {
XiongRequestMapping xiongRequestMapping = (XiongRequestMapping) clazz.getAnnotation(XiongRequestMapping.class);
baseUrl = xiongRequestMapping.value();
}
//獲取類中的方法對象
Method[] methods = clazz.getMethods();
for (Method method : methods) {
//查找被XiongRequestMapping修飾的方法
if (!method.isAnnotationPresent(XiongRequestMapping.class)) {
continue;
}
XiongRequestMapping xiongRequestMapping = method.getAnnotation(XiongRequestMapping.class);
String url = "/" + baseUrl + "/" + xiongRequestMapping.value();
//value中可能用戶填寫了 "/", 這里就會形成雙斜杠甚至多斜杠
url = url.replaceAll("/+", "/");
handlerMappings.add(new HandlerMapping(Pattern.compile(url), method, entry.getValue()));
System.out.println("mapped" + url + ":" + method.getName());
}
}
}
/**
* 實例對象屬性注入
*/
private void doAutowired() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
//獲取實例類的所有字段
Field[] fields = entry.getValue().getClass().getDeclaredFields();
//判斷field字段是否被@XiongAutowired修飾
for (Field field : fields) {
if (!field.isAnnotationPresent(XiongAutowired.class)) {
continue;
}
XiongAutowired xiongAutowired = field.getAnnotation(XiongAutowired.class);
String beanName = xiongAutowired.value();
if ("".equals(beanName)) {
beanName = toLowerFirstChar(field.getType().getSimpleName());
}
//設置私有屬性可訪問性
field.setAccessible(true);
//注入屬性值
try {
field.set(entry.getValue(), ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
continue;
}
}
}
}
/**
* 實例化掃描到的類,同時保存到IOC容器中
*/
private void doInstance() {
if (classNames.isEmpty()) {
return;
}
try {
for (String className : classNames) {
Class<?> clazz = Class.forName(className);
//被XiongController注解修飾的
if (clazz.isAnnotationPresent(XiongController.class)) {
Object instance = clazz.newInstance();
//beanName獲取
String beanName = toLowerFirstChar(clazz.getSimpleName());//這里一般實例名是類名首字母小寫
ioc.put(beanName, instance);
} else if (clazz.isAnnotationPresent(XiongService.class)) {
String beanName = toLowerFirstChar(clazz.getSimpleName());
//查看XiongService注解是否存在自定義命名
XiongService xiongService = clazz.getAnnotation(XiongService.class);
if (!"".equals(xiongService.value())) {
beanName = xiongService.value();
}
//生成實例
Object instance = clazz.newInstance();
ioc.put(beanName, clazz);
//為server的接口也綁定實例
for (Class<?> iFace : clazz.getInterfaces()) {
if (ioc.containsKey(iFace.getSimpleName())) {
throw new Exception("this beanName is exists");
}
ioc.put(toLowerFirstChar(iFace.getSimpleName()), instance);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 首字母轉小寫
*
* @param className
* @return
*/
private String toLowerFirstChar(String className) {
if (className != null) {
char[] chars = className.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
return className;
}
/**
* 掃描對應的包,拿到類名的全路徑,方便后面通過反射生成實例
*
* @param scanPackage
*/
private void doScanner(String scanPackage) {
//包名是通過 . 的形式,這里需要轉換成文件路徑的形式
URL url = this.getClass()
.getClassLoader()
.getResource("/" + scanPackage.replaceAll("\\.", "/"));
File classPath = new File(url.getFile());
//判斷是文件還是文件夾,如果是文件就需要判斷是否是以.class結尾的
for (File file : classPath.listFiles()) {
if (file.isDirectory()) {
//文件夾繼續深層次遍歷,知道找到文件
doScanner(scanPackage + "." + file.getName());
} else {
if (!file.getName().endsWith(".class")) {return;}
//類的全路徑
String className = (scanPackage + "." + file.getName()).replace(".class", "");
classNames.add(className);
}
}
}
/**
* 加載配置文件,這里的配置文件直接在web.xml中配置的contextConfigLocation為application.properties
* 主要是為了方便加載配置,如果用xml解析的話就麻煩一點
* 加載的配置文件主要是拿到需要掃描的包名
*
* @param contextConfigLocation
*/
private void doLoadConfig(String contextConfigLocation) {
InputStream fis = null;
fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
//讀取配置文件
try {
contextConfig.load(fis);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package org.xiong.v1.mvcframework.servlet2;
import org.xiong.v1.mvcframework.annotation.XiongRequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HandlerMapping {
/**
* url Pattern.compile(url)
*/
private Pattern pattern;
private Method method;
private Object controller;
/**
* 記錄參數與參數位置之間的關聯關系
*/
private Map<String, Integer> paramIndexMapping;
public HandlerMapping(Pattern pattern, Method method, Object controller) {
this.pattern = pattern;
this.method = method;
this.controller = controller;
paramIndexMapping = new HashMap<String, Integer>();
putParamIndexMapping(method);
}
public Pattern getPattern() {
return pattern;
}
public Method getMethod() {
return method;
}
public Object getController() {
return controller;
}
public Map<String, Integer> getParamIndexMapping() {
return paramIndexMapping;
}
private void putParamIndexMapping(Method method) {
//獲取方法參數上使用的注解
//一個參數可能有多個主機,一個方法可能會有多個參數,所以這里是二位數組
Annotation[][] pa = method.getParameterAnnotations();
for (int i = 0; i < pa.length; i++) {
for(Annotation a : pa[i]) {
if(a instanceof XiongRequestParam) {
String paramName = ((XiongRequestParam) a).value();
if(!"".equals(paramName)){
//表示用戶填寫了自定義參數名稱
paramIndexMapping.put(paramName, i);//記錄參數位置
} else {
//用戶沒有填寫的情況下,用參數名本身
Parameter[] parameters = method.getParameters();
paramIndexMapping.put(parameters[i].getName(), i);
}
}
}
}
//request,response參數位置保存
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> type = parameterTypes[i];
if (type == HttpServletRequest.class
|| type == HttpServletResponse.class){
paramIndexMapping.put(type.getName(), i);
}
}
}
/**
* 獲取url--->method的映射關系對象
* @return
*/
public static HandlerMapping getHandler(HttpServletRequest request, List<HandlerMapping> handlerMappings) {
//獲取訪問的url
String url = request.getRequestURI();
String contextPath = request.getContextPath();
//url中去掉contenxtpath得到從controller層出發的url
url.replaceAll(contextPath, "").replaceAll("/+", "/");
for (HandlerMapping handlerMapping : handlerMappings) {
Matcher matcher = handlerMapping.getPattern().matcher(url);
//循環匹配,找到對應的映射關系對象
if(!matcher.matches()) {continue;}
return handlerMapping;
}
return null;
}
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XiongAutowired {
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XiongController {
String value() default "";
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XiongRequestMapping {
String value() default "";
}
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XiongRequestParam {
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XiongService {
String value() default "";
}
package org.xiong.v1.mvc.action;
import org.xiong.v1.mvc.service.DemoService;
import org.xiong.v1.mvcframework.annotation.XiongAutowired;
import org.xiong.v1.mvcframework.annotation.XiongController;
import org.xiong.v1.mvcframework.annotation.XiongRequestMapping;
import org.xiong.v1.mvcframework.annotation.XiongRequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@XiongController
@XiongRequestMapping("/xiong")
public class DemoAction {
@XiongAutowired
private DemoService demoService;
@XiongRequestMapping("/query")
public void query(HttpServletRequest req, HttpServletResponse resp,
@XiongRequestParam("name") String name){
String result = demoService.get(name);
// String result = "My name is " + name;
try {
resp.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
@XiongRequestMapping("/add")
public void add(HttpServletRequest req, HttpServletResponse resp,
@XiongRequestParam("a") Integer a, @XiongRequestParam("b") Integer b){
try {
resp.getWriter().write(a + "+" + b + "=" + (a + b));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public interface DemoService {
String get(String name);
}
@XiongService
public class DemoServiceImpl implements DemoService {
@Override
public String get(String name) {
return "I am " + name;
}
}