一.手写MVC框架实现功能
(一)SpringMVC请求处理流程回顾
![](https://img-blog.csdnimg.cn/c213dcc18fed418f95574c83410b983e.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAZW50ZXJwYw==,size_20,color_FFFFFF,t_70,g_se,x_16)
(二)手写MVC框架主要实现功能
![](https://img-blog.csdnimg.cn/9059fcefa70b4c15ad211316782567fb.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAZW50ZXJwYw==,size_20,color_FFFFFF,t_70,g_se,x_16)
二. 准备阶段
(一)自定义注解
package com.lagou.edu.mvcframework.annotations;
import java.lang.annotation.*;
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouAutowired {
String value() default "";
}
package com.lagou.edu.mvcframework.annotations;
import java.lang.annotation.*;
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouController {
String value() default "";
}
package com.lagou.edu.mvcframework.annotations;
import java.lang.annotation.*;
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouRequestMapping {
String value() default "";
}
package com.lagou.edu.mvcframework.annotations;
import java.lang.annotation.*;
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouService {
String value() default "";
}
(二) 准备Handler方法
package com.lagou.demo.controller;
import com.lagou.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouController;
import com.lagou.edu.mvcframework.annotations.LagouRequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@LagouController
@LagouRequestMapping("/demo")
public class DemoController {
@LagouAutowired
private IDemoService demoService;
/**
* URL: /demo/query?name=lisi
* @param request
* @param response
* @param name
* @return
*/
@LagouRequestMapping("/query")
public String query(HttpServletRequest request, HttpServletResponse response,String name) {
return demoService.get(name);
}
}
(三)准备封装Handler方法相关信息及url和Method之间的映射关系
public class Handler {
private Object controller; // method.invoke(obj,)
private Method method;
private Pattern pattern; // spring中url是支持正则的
private Map<String,Integer> paramIndexMapping; // 参数顺序,是为了进行参数绑定,key是参数名,value代表是第几个参数 <name,2>
public Handler(Object controller, Method method, Pattern pattern) {
this.controller = controller;
this.method = method;
this.pattern = pattern;
this.paramIndexMapping = new HashMap<>();
}
...
一堆get、set
...
(四)准备包扫描,扫描注解相关工作
1.准备包扫描路径:springmvc.properties
scanPackage=com.lagou.demo
2. web.xml配置<servlet>