Spring5 - 30个类手写实战 - 打卡第三天(MVC)

相关文章:
Spring5 - 30个类手写实战 - 打卡第一天(V1版本)

Spring5 - 30个类手写实战 - 打卡第二天(IOC与DI)

Spring5 - 30个类手写实战 - 打卡第四天(AOP)

Spring5 - 30个类手写实战 - 打卡第五天(手绘IOC时序图)

1.MVC九大组件

序号组件名解释
1MultipartResolver多文件上传的组件
2LocalResolver本地语言环境
3ThemeResolver主题模块处理器
4HandlerMapping保存Url映射关系
5HandlerAdapter动态参数适配器
6HandlerExceptionResolver异常拦截器
7RequestToViewNameTranslator视图提取器,从reques中获取viewName
8ViewResolvers视图转换器,模板引擎
9FlashMapManager参数缓存器

核心组件执行流程

在这里插入图片描述

项目结构:

在这里插入图片描述

2.代码

PageAction

import com.liulin.spring.framework.annotation.LRequestParam;
import com.liulin.spring.framework.webmvc.servlet.LModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * Create by DbL on 2020/5/2 0002
 */
@LController
@LRequestMapping("/")
public class PageAction {

    @LAutowired
    IQueryService queryService;

    @LRequestMapping("/first.html")
    public LModelAndView query(@LRequestParam("coder") String teacher){
        String result = queryService.query(teacher);
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("coder", teacher);
        model.put("data", result);
        model.put("token", "123456");
        return new LModelAndView("first.html",model);
    }

}

first.html

<!DOCTYPE html>
<html lang="zh-cn">
<head>
	<meta charset="utf-8">
	<title>My SpringMVC模板引擎演示</title>
</head>
<center>
	<h1>大家好,我是¥{coder}<br/>欢迎大家一起来探索Spring的世界</h1>
	<h3>Hello,My name is ¥{coder}</h3>
	<div>{data}</div>
	Token值:¥{token}
</center>
</html>

LDispatcherServlet

package com.liulin.spring.framework.webmvc.servlet;

import com.liulin.spring.framework.annotation.*;
import com.liulin.spring.framework.context.LApplicationContext;

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.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Create by DbL on 2020/4/29 0029
 */
public class LDispatcherServlet extends HttpServlet {
    private LApplicationContext applicationContext;

    // IOC容器,key默认是类名首字母小写,value是对应的实例对象
    private List<LHandlerMapping> handlerMappings = new ArrayList<LHandlerMapping>();

    private Map<LHandlerMapping, LHandlerAdapter> handlerAdapters = new HashMap<LHandlerMapping, LHandlerAdapter>();

    private List<LViewResolver> viewResolvers = new ArrayList<LViewResolver>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
        // 6.委派,根据URL去找到一个对应的Method并通过response返回
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            try {
                processDispatchResult(req, resp, new LModelAndView("500"));
            } catch (Exception ex) {
                ex.printStackTrace();
                resp.getWriter().write("500 Exception , Detail : " + Arrays.toString(e.getStackTrace()));
            }
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 完成了对HandlerMapping的封装
        // 完成了对方法返回值的封装,ModelAndView

        // 1.通过URL获取一个HandlerMapping
        LHandlerMapping handler = getHandler(req);
        if (handler == null) {
            processDispatchResult(req, resp, new LModelAndView("404"));
            return;
        }
        // 2.根据一个HandlerMapping获取一个HandlerAdapter
        LHandlerAdapter ha = getHandlerAdapter(handler);

        // 3.解析某一个方法的形参和返回值之后,统一封装为ModelAndView对象
        LModelAndView mv = ha.handler(req, resp, handler);
        // 就把ModelAndView变成一个ViewResolver
        processDispatchResult(req, resp, mv);

    }

    private LHandlerAdapter getHandlerAdapter(LHandlerMapping handler) {
        if (this.handlerAdapters.isEmpty()){
            return null;
        }
        return this.handlerAdapters.get(handler);
    }

    private void processDispatchResult(HttpServletRequest req, HttpServletResponse resp, LModelAndView lModelAndView) throws Exception {
        if(lModelAndView == null){
            return;
        }
        if(this.viewResolvers.isEmpty()){
            return;
        }
        for(LViewResolver viewResolver : this.viewResolvers){
            LView view = viewResolver.resolverViewName(lModelAndView.getViewName());
            // 直接往浏览器输出
            view.render(lModelAndView.getModel(),req,resp);
            return;
        }
    }

    private LHandlerMapping getHandler(HttpServletRequest req) {
        if (this.handlerMappings.isEmpty()) {
            return null;
        }
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");

        for (LHandlerMapping mapping : handlerMappings) {
            Matcher matcher = mapping.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return mapping;
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 初始化Spring的核心IO容器
        applicationContext = new LApplicationContext(config.getInitParameter("contextConfigLocation"));

        // 初始化九大组件
        initStrategies(applicationContext);
        //================MVC部分==============//

        System.out.println("L Spring framework init success ");
    }

    private void initStrategies(LApplicationContext context) {
        // 多文件上传的组件
        //initMultipartResolver(context);
        // 初始化本地语言环境
        // initLocalResolver(context);
        // 初始化模板处理器
        // initThemResolver(context);
        // handlerMapping
        initHandlerMapping(context);
        // 初始化参数适配器
        initHandlerAdapters(context);
        // 初始化异常拦截器
        // initHandlerExceptionResolvers(context);
        // 初始化视图预处理器
        //initRequestToViewNameTranslator(context);
        // 初始化视图转换器
        initViewResolvers(context);
        // Flash管理器
        // initFlashMapManager(context);
    }

    private void initViewResolvers(LApplicationContext context) {
        String templateRoot = context.getConfig().getProperty("templateRoot");
        String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
        File templateRootDir = new File(templateRootPath);
        for(File file : templateRootDir.listFiles()){
            this.viewResolvers.add(new LViewResolver(templateRoot));
        }

    }

    private void initHandlerAdapters(LApplicationContext context) {
        for (LHandlerMapping handlerMapping : handlerMappings){
            this.handlerAdapters.put(handlerMapping,new LHandlerAdapter());
        }
    }

    private void initHandlerMapping(LApplicationContext context) {
        if (context.getBeanDefinitionCount() == 0) {
            return;
        }
        for (String beanName : context.getBeanDefinitionNames()) {
            Object instance = context.getBean(beanName);
            Class<?> clazz = instance.getClass();
            // 类没有加注解的跳过
            if (!clazz.isAnnotationPresent(LController.class)) {
                continue;
            }
            // 如果类上定义了路径,方法上的路径需要拼接上此路径
            String baseUrl = "";
            if (clazz.isAnnotationPresent(LRequestMapping.class)) {
                LRequestMapping Mapping = clazz.getAnnotation(LRequestMapping.class);
                baseUrl = Mapping.value();
            }
            // 只获取public的方法
            for (Method method : clazz.getMethods()) {
                // 方法没有加注解的跳过
                if (!method.isAnnotationPresent(LRequestMapping.class)) {
                    continue;
                }
                LRequestMapping requestMapping = method.getAnnotation(LRequestMapping.class);
                // 对于配置了“/” 和没有配置“/”的通过正则表达式统一处理
                // 将路径中的*改为正则表达式".*"的方式
                String regex = ("/" + baseUrl + "/" + requestMapping.value().replaceAll("\\*", ".*")).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                handlerMappings.add(new LHandlerMapping(pattern, instance, method));
                System.out.println("mapped : " + regex + " , " + method);
            }
        }
    }
}

LHandlerAdapter

package com.liulin.spring.framework.webmvc.servlet;

import com.liulin.spring.framework.annotation.LRequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Create by DbL on 2020/5/2 0002
 */
public class LHandlerAdapter {

    public LModelAndView handler(HttpServletRequest req, HttpServletResponse resp, LHandlerMapping handler) throws Exception {
        // 保存形参列表 将参数名称和参数的位置保存起来
        Map<String,Integer> paramIndexMapping = new HashMap<String,Integer>();
        // 通过运行时的状态去拿到注解的值
        Annotation[][] pa = handler.getMethod().getParameterAnnotations();
        for (int i = 0; i < pa.length; i++) {
            for (Annotation a : pa[i]) {
                if (a instanceof LRequestParam) {
                    String paramName = ((LRequestParam) a).value();
                    if (!"".equals(paramName.trim())) {
                        paramIndexMapping.put(paramName,i);
                    }
                }
            }
        }
        // 初始化
        Class<?>[] paramTypes = handler.getMethod().getParameterTypes();
        for (int i = 0; i < paramTypes.length; i++) {
            Class<?> paramterType = paramTypes[i];
            if (paramterType == HttpServletRequest.class || paramterType == HttpServletResponse.class) {
                paramIndexMapping.put(paramterType.getName(),i);
            }else if (paramterType == String.class) {

            }
        }
        // 拼接实参列表
        // http://localhost:8080/web/add.json?name=DBL&addr=chongqing
        Map<String, String[]> params = req.getParameterMap();

        Object[] paramValues = new Object[paramTypes.length];

        for(Map.Entry<String,String[]> param : params.entrySet()){
            String value = Arrays.toString(params.get(param.getKey()))
                    .replaceAll("\\[|\\]","")
                    .replaceAll("\\s+","");
            if(!paramIndexMapping.containsKey(param.getKey())){
                continue;
            }
            int index = paramIndexMapping.get(param.getKey());

            // 允许自定义的类型转换器Converter
            paramValues[index] = castStringValue(value,paramTypes[index]);
        }

       // String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
       // method.invoke(applicationContext.getBean(beanName), paramValues);
        if(paramIndexMapping.containsKey(HttpServletRequest.class.getName())){
            int index = paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[index] = req;
        }
        if(paramIndexMapping.containsKey(HttpServletResponse.class.getName())){
            int index = paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[index] = resp;
        }
        Object result = handler.getMethod().invoke(handler.getController(),paramValues);
        if (result == null || result instanceof  Void){
            return null;
        }
        boolean isModelAndView = handler.getMethod().getReturnType() == LModelAndView.class;
        if(isModelAndView){
            return (LModelAndView) result;
        }
        return null;
    }

    private Object castStringValue(String value, Class<?> paramType) {
        if(String.class == paramType){
            return value;
        }else if(Integer.class == paramType){
            return Integer.valueOf(value);
        }else if(Double.class == paramType){
            Double.valueOf(value);
        }else{
            if(value != null ){
                return value;
            }
        }
        return null;
    }
}

LHandlerMapping

package com.liulin.spring.framework.webmvc.servlet;

import java.lang.reflect.Method;
import java.util.regex.Pattern;

/**
 * Create by DbL on 2020/5/2 0002
 */
public class LHandlerMapping {
    private Pattern pattern; // URL
    private Method method; // 对应的Method
    private Object controller; // Method对应的实例对象

    public LHandlerMapping(Pattern pattern, Object controller, Method method) {
        this.pattern = pattern;
        this.method = method;
        this.controller = controller;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Object getController() {
        return controller;
    }

    public void setController(Object controller) {
        this.controller = controller;
    }
}

LModelAndView

package com.liulin.spring.framework.webmvc.servlet;

import java.util.Map;

/**
 * Create by DbL on 2020/5/1 0001
 */
public class LModelAndView {
    private String viewName;
    private Map<String,?> model;

    public LModelAndView(String viewName, Map<String, ?> model) {
        this.viewName = viewName;
        this.model = model;
    }

    public LModelAndView(String viewName) {
        this.viewName = viewName;
    }

    public String getViewName() {
        return viewName;
    }

    public Map<String, ?> getModel() {
        return model;
    }
}

LView

package com.liulin.spring.framework.webmvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Create by DbL on 2020/5/2 0002
 */
public class LView {
    private File viewFile;

    public LView(File templateFile) {
        this.viewFile = templateFile;
    }

    public void render(Map<String,?> model, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        StringBuffer sb = new StringBuffer();
        RandomAccessFile ra = new RandomAccessFile(this.viewFile,"r");
        String line = null;
        while(null != (line = ra.readLine())){
            line = new String(line.getBytes("ISO-8859-1"),"utf-8");
            Pattern pattern = Pattern.compile("¥\\{[^\\}]+\\}",Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()){
                String paramName = matcher.group();
                paramName = paramName.replaceAll("¥\\{|\\}","");
                Object paramValue = model.get(paramName);
                line = matcher.replaceFirst(makeStringForRegExp(paramValue.toString()));
                matcher = pattern.matcher(line);
            }
            sb.append(line);
        }
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(sb.toString());
    }

    //处理特殊字符
    public static String makeStringForRegExp(String str) {
        return str.replace("\\", "\\\\").replace("*", "\\*")
                .replace("+", "\\+").replace("|", "\\|")
                .replace("{", "\\{").replace("}", "\\}")
                .replace("(", "\\(").replace(")", "\\)")
                .replace("^", "\\^").replace("$", "\\$")
                .replace("[", "\\[").replace("]", "\\]")
                .replace("?", "\\?").replace(",", "\\,")
                .replace(".", "\\.").replace("&", "\\&");
    }
}

LViewResolver

package com.liulin.spring.framework.webmvc.servlet;

import java.io.File;

/**
 * Create by DbL on 2020/5/2 0002
 */
public class LViewResolver {
    private final String DEFAULT_TEMMPLATE_SUFFX = ".html";
    private File templateRootDir;

    public LViewResolver(String templateRoot) {
        String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
        templateRootDir = new File(templateRootPath);

    }

    public LView resolverViewName(String viewName) {
        if (null == viewName || "".equals(viewName.trim())) {
            return null;
        }
        viewName = viewName.endsWith(DEFAULT_TEMMPLATE_SUFFX) ? viewName : (viewName + DEFAULT_TEMMPLATE_SUFFX);
        File templateFile = new File((templateRootDir.getPath()+"/"+viewName).replaceAll("/+","/"));
        return new LView(templateFile);
    }
}

application.properties

scanPackage=com.liulin.demo
templateRoot=layouts

3 测试

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值