SpringMVC功能的实现主要由两部分实现
1. 配置ContextLoaderListener在Web容器启动过程中生成WebApplicationContext, 用来存储Web容器上下文,初始化Ioc等.
2. 配置DispatcherServlet,用来拦截Servlet请求,实现MVC功能.
其中WebApplicationContext我们在上一篇博客已经模拟实现了, 本文章接着模拟实现DispatcherServlet.
整个自定义框架主要类
- FLDispatcherServlet 继承自HttpServlet, 模拟实现DispatcherServlet
- FLHandlerMapping 存储请求Url与Controler.method的映射关系
- FLHandlerAdapter 于FLHandlerMapping 一对一关系, 用来存储FLHandlerMapping中所有Method的形参及形参位置.
- FLModelAndView 模拟ModelAndView ,View与Model的组合, 保存View对应的文件信息
- FLViewResolver 模拟View引擎,根据传进来的FLModelAndView , 找到模板文件,用model信息渲染View然后输出.
详细代码如下:
1. FLHandlerMapping
public class FLHandlerMapping {
private Object controller;
private Method method;
private Pattern urlPattern;
public FLHandlerMapping(Object controller, Method method, Pattern urlPattern) {
this.controller = controller;
this.method = method;
this.urlPattern = urlPattern;
}
}
类FLHandlerMapping 用来保存controller信息,及其对应的Url信息,此处用正则表达式模拟匹配的url.
2. FLHandlerAdapter
public class FLHandlerAdapter {
private FLHandlerMapping handlerMapping;
//记录本Method所有形式参数的位置,为了以后实例参数数组使用
private Map<String, Integer> methodParasMap = new HashMap<>();
public FLHandlerAdapter(FLHandlerMapping handlerMapping, Map<String, Integer> methodParasMap) {
this.handlerMapping = handlerMapping;
this.methodParasMap = methodParasMap;
}
//根据传的request,response,调用handler生成ModelAndView,
public FLModelAndView handler(HttpServletRequest request, HttpServletResponse response);
}
FLHandlerAdapter 保存有FLHandlerMapping 下所有Method及其对应形参信息(参数名字,参数位置等),
handler方法中根据形参从request中获取对应实参, 调用匹配的Method,返回FLModelAndView 信息.
后续在请求执行过程中再详解.
3. FLModelAndView
public class FLModelAndView {
private String viewName;
private Map<String,?> dataModel;
public FLModelAndView(String viewName, Map<String, ?> dataModel) {
this.viewName = viewName;
this.dataModel = dataModel;
}
}
FLModelAndView类比较简单, 只是保存viewName和要传递给模板引擎的Model信息
3. FLViewResolver
public class FLViewResolver {
private String viewName;
private File templateFile;
public FLViewResolver(String viewName, File templateFile) {
this.viewName = viewName;
this.templateFile = templateFile;
}
public String processViews(FLModelAndView mv) throws Exception{
//渲染生成view
}
}
FLViewResolver模拟模板引擎.主要用来根据viewName查找到相应的view模板文件,然后加上model信息,生成view返回给客户端.
3. FLDispatcherServlet
核心类,
继承自HttpServlet,用来处理web容器发过来的request请求.
public class FLDispatcherServlet extends HttpServlet {
private final String LOCATION = "contextConfigLocation";
FLWebApplicationContext applicationContext = null;
private List<FLHandlerMapping> handlerMappings = new ArrayList<>();
private Map<FLHandlerMapping, FLHandlerAdapter> handlerAdapterMap = new HashMap<>();
private List<FLViewResolver> viewResolvers = new ArrayList<>();
@Override