参考文章

一、了解SpringMVC运行流程及九大组件

1.SpringMVC的运行流程

1)用户发送请求至前端控制器DispatcherServlet

2)DispatcherServlet收到请求调用HandlerMapping处理器映射器

3)处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet

4)DispatcherServlet通过HandlerAdapter处理器适配器调用处理器

5)执行处理器(Controller,也叫后端控制器)

6)Controller执行完成返回ModelAndView

7)HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet

8)DispatcgerServlet将ModelAndView传给ViewReslover视图解析器

9)ViewResolver解析后返回具体View

10)DispatcherServlet对View进行渲染视图(将模型数据填充至视图中)

11)DispatcherServlet响应用户

从上面可以看出,DispatcherServlet有接受请求、响应结果、转发等作用。有了DispatcherServlet之后,可以减少组件之间的耦合度。

2、Spring mvc的9大组件

protected void initStrategies(ApplicationContext context) {
//用于处理上传请求。处理方法是将普通的request包装成MultipartHttpServletRequest,后者可以直接调用getFile方法获取File.
initMultipartResolver(context); //SpringMVC主要有两个地方用到了Locale:一是ViewResolver视图解析的时候;二是用到国际化资源或者主题的时候。
initLocaleResolver(context); //用于解析主题。SpringMVC中一个主题对应一个properties文件,里面存放着跟当前主题相关的所有资源、
//如图片、css样式等。SpringMVC的主题也支持国际化,
initThemeResolver(context); //用来查找Handler的。
initHandlerMappings(context); //从名字上看,它就是一个适配器。Servlet需要的处理方法的结构却是固定的,都是以request和response为参数的方法。
//如何让固定的Servlet处理方法调用灵活的Handler来进行处理呢?这就是HandlerAdapter要做的事情
initHandlerAdapters(context); //其它组件都是用来干活的。在干活的过程中难免会出现问题,出问题后怎么办呢?
//这就需要有一个专门的角色对异常情况进行处理,在SpringMVC中就是HandlerExceptionResolver。
initHandlerExceptionResolvers(context); //有的Handler处理完后并没有设置View也没有设置ViewName,这时就需要从request获取ViewName了,
//如何从request中获取ViewName就是RequestToViewNameTranslator要做的事情了。
initRequestToViewNameTranslator(context); //ViewResolver用来将String类型的视图名和Locale解析为View类型的视图。
//View是用来渲染页面的,也就是将程序返回的参数填入模板里,生成html(也可能是其它类型)文件。
initViewResolvers(context); //用来管理FlashMap的,FlashMap主要用在redirect重定向中传递参数。
initFlashMapManager(context);
}  

二、自己实现SpringMVC功能分析

以下主要实现SpringMVC的配置加载、实例化扫描的包、HandlerMapping的url映射到对应的Controller的method上,异常的拦截和动态调用后返回结果输出给浏览器的功能。

1、读取配置

从图中可以看出,SpringMVC本质上是一个Servlet,这个Servlet继承自HttpServlet

FrameworkServlet负责初始化SpringMVC的容器,并将Spring容器设置为父容器。

为了读取web.xml中的配置,我们用到ServletConfig这个类,它代表当前Servlet在web.xml中的配置信息。通过web.xml中加载我们自己写的MyDispatcherServlet和读取配置文件。

2.初始化阶段

由上可知,DispatcherServlet的initStrategies方法会初始化9大组件,但是我们只实现最基本的组件而不是全部。

按顺序包括:

  • 加载配置文件
  • 扫描用户配置包下面所有的类
  • 拿到扫描到的类,通过反射机制,实例化。并且放到ioc容器中(Map的键值对beanName-bean)beanname默认是首字母小写
  • 初始化HandlerMapping,这里其实是把url和method对应起来放在一个k-v的Map中,在运行阶段取出

3、运行阶段

每一次请求将会调用doGet或doPost方法,所以统一运行阶段都放在doDispatcher方法里处理,它会根据url请求去HandlerMapping中匹配到对应的Method,然后利用反射机制调用Controller中的url对应的方法,并得到结果返回,按顺序包括如下功能:

  • 异常的拦截
  • 获取请求传入的参数并处理参数
  • 通过初始化好的handlerMapping中拿出url对应的方法名,反射调用

三、写SpringMVC框架

建立maven工程

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.slp</groupId>
<artifactId>sanglpMVC</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>sanglpMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
</dependencies> </dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>sanglpMVC</finalName>
</build>
</project>

web.xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>MySpringMVC</servlet-name>
<servlet-class>com.slp.servlet.MyDispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MySpringMVC</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>  

  

application.properties

scanPackage=com.slp.core  

注解:

package com.slp.annotation;

import java.lang.annotation.*;

/**
* @author sanglp
* @create 2018-03-16 14:18
* @desc 自定义控制器注解
**/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyController {
/**
* 表示给controller注册别名
* @return
*/
String value() default "";
}
package com.slp.annotation;

import java.lang.annotation.*;

/**
* @author sanglp
* @create 2018-03-16 14:20
* @desc 自定义映射注解,类和方法上
**/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestMapping { /**
* 表示该方法的url
* @return
*/
String value() default "";
}
package com.slp.annotation;

import java.lang.annotation.*;

/**
* @author sanglp
* @create 2018-03-16 14:20
* @desc 自定义请求参数注解 只能在方法上
**/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestParam { /**
* 表示参数的别名 必填
* @return
*/
String value();
}

 

测试控制类

package com.slp.core.controller;

import com.slp.annotation.MyController;
import com.slp.annotation.MyRequestMapping;
import com.slp.annotation.MyRequestParam; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* @author sanglp
* @create 2018-03-16 14:20
* @desc 控制器测试
**/
@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();
}
}
}

 

转发控制器:

package com.slp.servlet;

import com.slp.annotation.MyController;
import com.slp.annotation.MyRequestMapping; 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.reflect.Method;
import java.net.URL;
import java.util.*; /**
* @author sanglp
* @create 2018-03-16 14:19
* @desc 自定义转发器
**/
public class MyDispatcherServlet extends HttpServlet {
private Properties properties = new Properties();
private List<String> classNames = new ArrayList<String>();
private Map<String, Object> ioc = new HashMap<String,Object>();
private Map<String, Method> handlerMapping = new HashMap<String, Method>();
private Map<String, Object> controllerMap =new HashMap<String, Object>();
@Override
public void init(ServletConfig config) throws ServletException{
//1.加载配置文件
System.out.println("configLocation:"+config.getInitParameter("contextConfigLocation"));
//doLoadConfig(config.getInitParameter("contextConfigLocation"));
doLoadConfig("application.properties");
//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.doGet(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求
try {
this.doDispatch(req,resp);
} catch (Exception e) {
e.printStackTrace();
}
} 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 (Map.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);//obj是method所对应的实例 在ioc容器中
} catch (Exception e) {
e.printStackTrace();
}
} private void doLoadConfig(String location){
//把web.xml中的contextConfigLocation对应value值的文件加载到留里面
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(location);
try {
//用Properties文件加载文件里的内容
properties.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
//关流
if(null!=resourceAsStream){
try {
resourceAsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void doScanner(String packageName) {
System.out.println("packageName:"+packageName);
//把所有的.替换成/
URL url =this.getClass().getClassLoader().getResource("/"+packageName.replaceAll(".", "/"));
System.out.println("url:"+url);
File dir = new File(url.getFile());
System.out.println("dir.listFiles():"+dir.exists() +" "+dir.getName()+" "+ dir.listFiles());
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 {
//把类搞出来,反射来实例化(只有加@MyController需要实例化)
Class<?> clazz =Class.forName(className);
if(clazz.isAnnotationPresent(MyController.class)){
ioc.put(toLowerFirstWord(clazz.getSimpleName()),clazz.newInstance());
}else{
continue;
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
} private void initHandlerMapping(){
if(ioc.isEmpty()){
return;
}
try {
for (Map.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);
}
}

四、自定义注解

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
String description();
String author();
int age() default 10;
}

首先这不是一个接口它是使用时@interface关键字定义的一个注解。然后我们看下面的几个方法:String description(),虽然他很类似于接口中的方法,其实它在注解里面只是一个成员变量(成员以无参无异常的方式声明),int age()  default 10;(变量可以设定默认值)。

最后:成员类型是受限制的,合法的类型包括基本的数据类型以及String ,Class Annotation  Enummeration等

如果注解只有一个成员,则成员名必须取名为value() 在使用时可以忽略成员名和赋值号

注解类可以没有成员,没有成员的注解称为标志注解  

 

元注解:

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented

 @Target是这个注解的作用域,有

public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE, /** Field declaration (includes enum constants) */
FIELD, /** Method declaration */
METHOD, /** Formal parameter declaration */
PARAMETER, /** Constructor declaration */
CONSTRUCTOR, /** Local variable declaration */
LOCAL_VARIABLE, /** Annotation type declaration */
ANNOTATION_TYPE, /** Package declaration */
PACKAGE, /**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER, /**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}

 @Retention是它的生命周期

public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE, /**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS, /**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}

@Inherited是标识性的元注解,它允许子注解继承他

@Documented,生成javadoc时会包含注解

/**
* Indicates that annotations with a type are to be documented by javadoc
* and similar tools by default. This type should be used to annotate the
* declarations of types whose annotations affect the use of annotated
* elements by their clients. If a type declaration is annotated with
* Documented, its annotations become part of the public API
* of the annotated elements.
*
* @author Joshua Bloch
* @since 1.5
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

  

  

 

  

  

【Spring系列】自己手写一个 SpringMVC 框架的更多相关文章

  1. Spring系列之手写一个SpringMVC

    目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 Spring系列之AOP的原理及手动实现 Spring系列之手写注解与配置文件的解析 引言 在前面的几个章节中我 ...

  2. 看年薪50W的架构师如何手写一个SpringMVC框架

    前言 做 Java Web 开发的你,一定听说过SpringMVC的大名,作为现在运用最广泛的Java框架,它到目前为止依然保持着强大的活力和广泛的用户群. 本文介绍如何用eclipse一步一步搭建S ...

  3. 自己手写一个SpringMVC 框架

    一.了解SpringMVC运行流程及九大组件 1.SpringMVC 的运行流程   · 用户发送请求至前端控制器DispatcherServlet · DispatcherServlet收到请求调用 ...

  4. 自己手写一个SpringMVC框架

    前端框架很多,但没有一个框架称霸,后端框架现在Spring已经完成大一统.所以学习Spring是Java程序员的必修课. Spring框架对于Java后端程序员来说再熟悉不过了,以前只知道它用的反射实 ...

  5. 手写一个SpringMVC框架(转)

    一:梳理SpringMVC的设计思路 本文只实现自己的@Controller.@RequestMapping.@RequestParam注解起作用,其余SpringMVC功能读者可以尝试自己实现. 1 ...

  6. 剖析手写Vue,你也可以手写一个MVVM框架

    剖析手写Vue,你也可以手写一个MVVM框架# 邮箱:563995050@qq.com github: https://github.com/xiaoqiuxiong 作者:肖秋雄(eddy) 温馨提 ...

  7. 手写迷你SpringMVC框架

    前言 学习如何使用Spring,SpringMVC是很快的,但是在往后使用的过程中难免会想探究一下框架背后的原理是什么,本文将通过讲解如何手写一个简单版的springMVC框架,直接从代码上看框架中请 ...

  8. 【Spring系列】- 手写模拟Spring框架

    简单模拟Spring 生命不息,写作不止 继续踏上学习之路,学之分享笔记 总有一天我也能像各位大佬一样 一个有梦有戏的人 @怒放吧德德 分享学习心得,欢迎指正,大家一起学习成长! 前言 上次已经学习了 ...

  9. Spring系列之手写注解与配置文件的解析

    目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 Spring系列之AOP的原理及手动实现 引入 在前面我们已经完成了IOC,DI,AOP的实现,基本的功能都已经 ...

随机推荐

  1. C# 枚举使用和对应说明获取实例

    1.定义枚举 /// <summary> /// 订单状态 /// </summary> public enum OrderState { 待支付 = 1, 待处理 = 2, ...

  2. C# 扩展方法 白话总结

    我们在变成的时候时常遇到这样的问题,new了一个系统内的对象之后,我们想要对该对象有一个方法可是却点不出来,说明该对象本身没有声明该方法,可是微软又不允许我们去该对象的代码,怎么办? 在C# 3.0  ...

  3. The Moving Points HDU - 4717

    There are N points in total. Every point moves in certain direction and certain speed. We want to kn ...

  4. 如何在Java应用中提交Spark任务?

    最近看到有几个Github友关注了Streaming的监控工程--Teddy,所以思来想去还是优化下代码,不能让别人看笑话,是不.于是就想改在一下之前最丑陋的一个地方--任务提交 本博客内容基于Spa ...

  5. Codeforces Round #466 (Div. 2)

    所有的题目都可以在CodeForces上查看 中间看起来有很多场比赛我没有写了 其实是因为有题目没改完 因为我不想改,所以就没有写了(大部分题目还是改完了的) 我还是觉得如果是打了的比赛就一场一场写比 ...

  6. 【Luogu1876】开灯(数论)

    [Luogu1876]开灯(数论) 题面 题目描述 首先所有的灯都是关的(注意是关!),编号为1的人走过来,把是一的倍数的灯全部打开,编号为二的的把是二的倍数的灯全部关上,编号为3的人又把是三的倍数的 ...

  7. Net 面试随想

    佳节已去,至今已半月有余,近来园中唱衰net的声音幽幽而起,net不成熟的大环境一直被作为诟病,net core的跨平台去年抄的火热,是否为net 崛起的最后一根稻草,结合我面试的情况,作为小白,嘟囔 ...

  8. python数据类型:序列(字符串,元组,列表,字典)

    序列通常有2个特点: 1,可以根据索引取值 2,可以切片操作 字符串,元组,列表,字典,都可以看做是序列类型 我的操作环境:Ubuntu16.04+python2.7 一.字符串类型 >按索引获 ...

  9. 题目1031:xxx定律

    题目描述: 对于一个数n,如果是偶数,就把n砍掉一半:如果是奇数,把n变成 3*n+ 1后砍掉一半,直到该数变为1为止. 请计算需要经过几步才能将n变到1,具体可见样例. 输入: 测试包含多个用例,每 ...

  10. delphi JPG图片 旋转 切边 缩放

    unit UCutFigure_JPG; //JPG 切图 interface uses Windows, Messages, SysUtils, Variants, Classes, Graphic ...