1. 本文主要是利用少量代碼編寫(xiě)出spring,springmvc的核心實(shí)現(xiàn)原理,僅供參考牵咙。實(shí)際與spring內(nèi)置實(shí)現(xiàn)還有一定的差距鳖昌。希望以此文幫助大家了解spring實(shí)現(xiàn)的一些思想胖眷,謝謝恕酸。
2. 涉及功能,IOC畔勤,DI蕾各,HandleMapping。
3. 邏輯線庆揪,從web.xml入手>>>>加載配置>>>> 掃描包路徑>>>>實(shí)例化對(duì)象保存到ioc>>>>>Autowired注入>>>>handleMapping初始化式曲。
4. 開(kāi)擼
<?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作為配置文件缸榛,簡(jiǎn)化了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;
/**
* 升級(jí)版吝羞,不適用map保存url與method之間的關(guān)聯(lián)關(guān)系,使用List<HandlerMaping>存儲(chǔ)
*/
public class XiongDispatcherServlet2 extends HttpServlet {
private Properties contextConfig = new Properties();
/**
* 存儲(chǔ)所有掃描出來(lái)的類(lèi)
*/
private List<String> classNames = new ArrayList<String>();
/**
* 模擬IOC容器
*/
private Map<String, Object> ioc = new HashMap<String, Object>();
/**
* 保存controller中requestmapping和method之間的對(duì)應(yīng)關(guān)系
*/
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 {
//委派模式内颗,分發(fā)
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對(duì)應(yīng)的method, 如果沒(méi)有就404
if (handlerMapping == null) {
resp.getWriter().write("404 Not Found");
return;
}
Method method = handlerMapping.getMethod();
//獲取請(qǐng)求參數(shù), 這個(gè)方法獲取的參數(shù)是不可修改的钧排,只能讀取,安全規(guī)范WebLogic均澳,Tomcat恨溜,Resin,JBoss等服務(wù)器均實(shí)現(xiàn)了此規(guī)范
Map<String, String[]> params = req.getParameterMap();
//獲取方法的形參列表
Class<?>[] parameterTypes = method.getParameterTypes();
//保存賦值參數(shù)的位置
Object[] paramValues = new Object[parameterTypes.length];
//按照參數(shù)的位置動(dòng)態(tài)賦值
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());
//參數(shù)類(lèi)型可能是其他類(lèi)型负懦,這里需要進(jìn)行相關(guān)轉(zhuǎn)換筒捺,目前demo中只對(duì)integer double進(jìn)行轉(zhuǎn)換(多種類(lèi)型轉(zhuǎn)換,避免多個(gè)if else可以使用策略模式)
paramValues[index] = covert(parameterTypes[index],value);
}
}
//設(shè)置方法中request,response的值
int reqIndex = handlerMapping.getParamIndexMapping().get(HttpServletRequest.class.getName());
paramValues[reqIndex] = req;
int respIndex = handlerMapping.getParamIndexMapping().get(HttpServletResponse.class.getName());
paramValues[respIndex] = resp;
//利用反射執(zhí)行方法
method.invoke(handlerMapping.getController(), paramValues);
}
/**
* 將string類(lèi)型轉(zhuǎn)換成其他類(lèi)型的參數(shù)
* 這里暫時(shí)只寫(xiě)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. 掃描相關(guān)類(lèi)
doScanner(contextConfig.getProperty("scanPackage"));
//3. 初始化類(lèi)實(shí)例,放入到IOC容器
doInstance();
//4. 依賴注入
doAutowired();
//5. 初始化HandlerMapping
initHandlerMapping();
//完成
}
/**
* 初始化XiongRequestMapping url與method之間的關(guān)系
*/
private void initHandlerMapping() {
if (ioc.isEmpty()) {
return;
}
//找被XiongController修飾的類(lèi)纸厉,找到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();
}
//獲取類(lèi)中的方法對(duì)象
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中可能用戶填寫(xiě)了 "/", 這里就會(huì)形成雙斜杠甚至多斜杠
url = url.replaceAll("/+", "/");
handlerMappings.add(new HandlerMapping(Pattern.compile(url), method, entry.getValue()));
System.out.println("mapped" + url + ":" + method.getName());
}
}
}
/**
* 實(shí)例對(duì)象屬性注入
*/
private void doAutowired() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
//獲取實(shí)例類(lèi)的所有字段
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());
}
//設(shè)置私有屬性可訪問(wèn)性
field.setAccessible(true);
//注入屬性值
try {
field.set(entry.getValue(), ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
continue;
}
}
}
}
/**
* 實(shí)例化掃描到的類(lèi)五嫂,同時(shí)保存到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());//這里一般實(shí)例名是類(lèi)名首字母小寫(xiě)
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();
}
//生成實(shí)例
Object instance = clazz.newInstance();
ioc.put(beanName, clazz);
//為server的接口也綁定實(shí)例
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();
}
}
/**
* 首字母轉(zhuǎn)小寫(xiě)
*
* @param className
* @return
*/
private String toLowerFirstChar(String className) {
if (className != null) {
char[] chars = className.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
return className;
}
/**
* 掃描對(duì)應(yīng)的包颗品,拿到類(lèi)名的全路徑肯尺,方便后面通過(guò)反射生成實(shí)例
*
* @param scanPackage
*/
private void doScanner(String scanPackage) {
//包名是通過(guò) . 的形式,這里需要轉(zhuǎn)換成文件路徑的形式
URL url = this.getClass()
.getClassLoader()
.getResource("/" + scanPackage.replaceAll("\\.", "/"));
File classPath = new File(url.getFile());
//判斷是文件還是文件夾躯枢,如果是文件就需要判斷是否是以.class結(jié)尾的
for (File file : classPath.listFiles()) {
if (file.isDirectory()) {
//文件夾繼續(xù)深層次遍歷则吟,知道找到文件
doScanner(scanPackage + "." + file.getName());
} else {
if (!file.getName().endsWith(".class")) {return;}
//類(lèi)的全路徑
String className = (scanPackage + "." + file.getName()).replace(".class", "");
classNames.add(className);
}
}
}
/**
* 加載配置文件,這里的配置文件直接在web.xml中配置的contextConfigLocation為application.properties
* 主要是為了方便加載配置锄蹂,如果用xml解析的話就麻煩一點(diǎn)
* 加載的配置文件主要是拿到需要掃描的包名
*
* @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;
/**
* 記錄參數(shù)與參數(shù)位置之間的關(guān)聯(lián)關(guān)系
*/
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) {
//獲取方法參數(shù)上使用的注解
//一個(gè)參數(shù)可能有多個(gè)主機(jī)氓仲,一個(gè)方法可能會(huì)有多個(gè)參數(shù),所以這里是二位數(shù)組
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)){
//表示用戶填寫(xiě)了自定義參數(shù)名稱
paramIndexMapping.put(paramName, i);//記錄參數(shù)位置
} else {
//用戶沒(méi)有填寫(xiě)的情況下得糜,用參數(shù)名本身
Parameter[] parameters = method.getParameters();
paramIndexMapping.put(parameters[i].getName(), i);
}
}
}
}
//request,response參數(shù)位置保存
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的映射關(guān)系對(duì)象
* @return
*/
public static HandlerMapping getHandler(HttpServletRequest request, List<HandlerMapping> handlerMappings) {
//獲取訪問(wèn)的url
String url = request.getRequestURI();
String contextPath = request.getContextPath();
//url中去掉contenxtpath得到從controller層出發(fā)的url
url.replaceAll(contextPath, "").replaceAll("/+", "/");
for (HandlerMapping handlerMapping : handlerMappings) {
Matcher matcher = handlerMapping.getPattern().matcher(url);
//循環(huán)匹配敬扛,找到對(duì)應(yīng)的映射關(guān)系對(duì)象
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;
}
}