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;
}
}