手写spring+springmvc+mybatis框架篇【springmvc】

知音专栏

程序员的出路

写程序时该追求什么,什么是次要的?

如何准备Java初级和高级的技术面试

上一篇:手写spring+springmvc+mybatis框架篇【springIOC容器】

题外话:技术交流,欢迎加入QQ群:696209224 。广告勿扰!

先放一张网上的很好的一张原理图

图片出自,这篇博客原理也写的很清晰明了。我的实现也是借鉴了这张图

手写spring+springmvc+mybatis框架篇【springmvc】

https://www.cnblogs.com/xiaoxi/p/6164383.html

先说一下我的实现思路:

1 在MyDispatcherServlet中的servlet初始化的时候,绑定标有@MyController注解类下面的@MyRequestMappign的value值和对应的方法。绑定的方式是放在map集合中。这个map集合就是上图说的handlerMapping,返回的handler也就是一组键值对。

2 找到对应的方法后,反射执行方法,在方法中创建一个modelandview对象,model也就是我们说的数据域,view返回的是一个视图名称,也就是我们说的视图域,当然,我这里只有jsp,spring做的很复杂。支持多种类型。最后所谓的渲染,也就是将这个数据域中的数据会添加到request请求中,然后转发。返回客户端。

3 绑定参数模型这一部分略为复杂。在下面讲解

下面是MyDispatcherServlet

这个servlet的作用就是接收用户请求,然后派发注意标红处bingdingMethodParamters方法,这个方法实现了参数的绑定。


package spring.servlet;

import lombok.extern.slf4j.Slf4j;
import spring.factory.InitBean;
import spring.springmvc.Binding;
import spring.springmvc.Handler;
import spring.springmvc.MyModelAndView;
import spring.springmvc.ViewResolver;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static spring.springmvc.BindingRequestAndModel.bindingRequestAndModel;
/**
* Created by Xiao Liang on 2018/6/27.
*/
@WebServlet(name = "MyDispatcherServlet")
@Slf4j
public class MyDispatcherServlet extends HttpServlet {
   /**
    * 初始化servlet,将bean容器和HandlerMapping放到servlet的全局变量中
    */
   @Override
   public void init() {
       InitBean initBean = new InitBean();
       initBean.initBeans();
       //根据bean容器中注册的bean获得HandlerMapping
       Map<String, Method> bindingRequestMapping = Handler.bindingRequestMapping(initBean.beanContainerMap);
       ServletContext servletContext = this.getServletContext();
       servletContext.setAttribute("beanContainerMap", initBean.beanContainerMap);
       servletContext.setAttribute("bindingRequestMapping", bindingRequestMapping);
   }
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       try {
           doDispatch(request, response);
       } catch (Exception e) {
           log.error("控制器处理异常");
           e.printStackTrace();
       }
   }
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request, response);
   }
   //接收到请求后转发到相应的方法上
   private void doDispatch(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException, InstantiationException {
       ServletContext servletContext = this.getServletContext();
       //获取扫描controller注解后url和方法绑定的mapping,也就是handlerMapping
       Map<String, Method> bindingRequestMapping =
               (Map<String, Method>) servletContext.getAttribute("bindingRequestMapping");
       //获取实例化的bean容器
       Map<String, Object> beanContainerMap = (Map<String, Object>) servletContext.getAttribute("beanContainerMap");
       String url = request.getServletPath();
       Set<Map.Entry<String, Method>> entries = bindingRequestMapping.entrySet();
       List<Object> resultParameters = Binding.bingdingMethodParamters(bindingRequestMapping, request);
       for (Map.Entry<String, Method> entry :
               entries) {
           if (url.equals(entry.getKey())) {
               Method method = entry.getValue();
               Class<?> returnType = method.getReturnType();
                   //如果返回值是MyModelAndView,开始绑定
               if ("MyModelAndView".equals(returnType.getSimpleName())){
                   Object object = beanContainerMap.get(method.getDeclaringClass().getName());
                   //获取springmvc.xml中配置的视图解析器
                   ViewResolver viewResolver = (ViewResolver) beanContainerMap.get("spring.springmvc.ViewResolver");
                   String prefix = viewResolver.getPrefix();
                   String suffix = viewResolver.getSuffix();
                   MyModelAndView myModelAndView = (MyModelAndView) method.invoke(object, resultParameters.toArray());
                   //将request和model中的数据绑定,也就是渲染视图
                   bindingRequestAndModel(myModelAndView,request);
                   String returnViewName = myModelAndView.getView();
                   //返回的路径
                   String resultAddress = prefix + returnViewName + suffix;
                   try {
                       request.getRequestDispatcher(resultAddress).forward(request,response);
                   } catch (ServletException e) {
                       e.printStackTrace();
                   }
               }
           }
       }
   }
}

首先是绑定方法和url,是Handler类,用如下对象绑定

Map<String, Method> handlerMapping = new ConcurrentHashMap<>();
package spring.springmvc;
import lombok.extern.slf4j.Slf4j;
import spring.Utils.AnnotationUtils;
import spring.annotation.MyController;
import spring.annotation.MyRequestMapping;
import spring.exception.springmvcException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
* @ClassName Handler
* @Description  遍历bean容器,在有controller注解的类中有requestmapping扫描的方法,则将方法和url和方法绑定
* @Data 2018/7/3
* @Author xiao liang
*/
@Slf4j
public class Handler {
   public static Map<String, Method> bindingRequestMapping(Map<String, Object> beanContainerMap){
       Map<String, Method> handlerMapping = new ConcurrentHashMap<>();
       if (beanContainerMap != null){
           Set<Map.Entry<String, Object>> entries = beanContainerMap.entrySet();
           for (Map.Entry<String, Object> entry :
                   entries) {
               Class aClass = entry.getValue().getClass();
               Annotation annotation = aClass.getAnnotation(MyController.class);
               Method[] methods = aClass.getMethods();
               if (!AnnotationUtils.isEmpty(annotation) && methods != null){
                   for (Method method:
                           aClass.getMethods()) {
                       MyRequestMapping requestMappingAnnotation = method.getAnnotation(MyRequestMapping.class);
                       if (!AnnotationUtils.isEmpty(requestMappingAnnotation)){
                           String key = requestMappingAnnotation.value();
                           handlerMapping.put(key,method);
                       }
                   }
               }
           }
       }
       else{
           throw new springmvcException("实例化bean异常,没有找到容器");
       }
       return handlerMapping;
   }
}

参数绑定支持

  1. @MyRequestMapping(用来绑定简单数据类型)

  2. @MyModelAndAttribute(绑定实体类)

  3. 不写注解,直接写实体类。

下面先贴一下这一部分的结构关系图

手写spring+springmvc+mybatis框架篇【springmvc】

这里用多态的设计思想,对于bindingParamter方法写了两种实现,方便大家自行扩展

package spring.springmvc;

import spring.Utils.AnnotationUtils;
import spring.Utils.isBasicTypeUtils;
import spring.annotation.MyModelAttribute;
import spring.annotation.MyRequstParam;
import spring.exception.springmvcException;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @ClassName Binding
* @Description
* @Data 2018/7/4
* @Author xiao liang
*/
public class Binding {
   public static  List<Object> bingdingMethodParamters(Map<String, Method> bindingRequestMapping, HttpServletRequest request) {
       List<Object> resultParameters  = new ArrayList<>();
       Set<Map.Entry<String, Method>> entries = bindingRequestMapping.entrySet();
       for (Map.Entry<String, Method> entry :
               entries) {
           Method method = entry.getValue();
           Parameter[] parameters = method.getParameters();
           for (Parameter parameter :
                   parameters) {       //遍历每个参数,如果参数存在注解,将这个参数添加到resultParameters中
               if (!AnnotationUtils.isEmpty(parameter.getAnnotations())){
                   Object resultParameter = null;
                   try {
                       resultParameter = bingdingEachParamter(parameter, request);
                   } catch (IllegalAccessException e) {
                       e.printStackTrace();
                       throw new springmvcException("绑定参数异常");
                   } catch (NoSuchMethodException e) {
                       e.printStackTrace();
                       throw new springmvcException("绑定参数异常");
                   } catch (InstantiationException e) {
                       e.printStackTrace();
                       throw new springmvcException("绑定参数异常");
                   }
                   resultParameters.add(resultParameter);
               }
           }
       }
       return resultParameters;
   }
private static Object bingdingEachParamter(Parameter parameter, HttpServletRequest request) throws IllegalAccessException, NoSuchMethodException, InstantiationException {
        //如果注解是MyRequstParam,则用BindingByMyRequstParam来执行装配
        if (!AnnotationUtils.isEmpty(parameter.getAnnotation(MyRequstParam.class))){
            BindingParamter bindingParamter = new BindingByMyRequstParam();
            Object resultParameter = bindingParamter.bindingParamter(parameter, request);
            return resultParameter;
        }
        //如果注解是MyModelAttribute,则用BindingByMyModelAttribute来执行装配
        else if (!AnnotationUtils.isEmpty(parameter.getAnnotation(MyModelAttribute.class))){
            BindingParamter bindingParamter = new BindingByMyModelAttribute();
            Object resultParameter = bindingParamter.bindingParamter(parameter,request);
            return resultParameter;
        }
        //在没有注解的时候,自动识别,如果是基本数据类型用MyRequstParam装配,如果是用户自定义类型用MyModelAttribute装配
        else if(parameter.getAnnotations() == null || parameter.getAnnotations().length ==0){
            boolean flag = isBasicTypeUtils.isBasicType(parameter.getType().getSimpleName());
            if (flag){
                BindingParamter bindingParamter = new BindingByMyRequstParam();
                Object resultParameter = bindingParamter.bindingParamter(parameter, request);
                return resultParameter;
            }
            else{
                BindingParamter bindingParamter = new BindingByMyModelAttribute();
                Object resultParameter = bindingParamter.bindingParamter(parameter,request);
                return resultParameter;
            }
        }
        return null;
    }
}

下面是接口BindingParamter 和两个实现类BindingByMyModelAttribute和BindingByMyRequstParam

package spring.springmvc;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;

/**
* @ClassName BindingRoles
* @Description
* @Data 2018/7/4
* @Author xiao liang
*/
public interface BindingParamter {

    Object bindingParamter(Parameter parameter, HttpServletRequest request) throws IllegalAccessException, InstantiationException, NoSuchMethodException;

}

package spring.springmvc;

import spring.Utils.StringUtils;
import spring.annotation.MyRequstParam;
import spring.exception.springmvcException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;

/**
* @ClassName BindingByMyRequstParam
* @Description 参数注解是MyMyRequstParam时,绑定数据的类
* @Data 2018/7/4
* @Author xiao liang
*/
public class BindingByMyRequstParam implements BindingParamter {
   @Override
   public Object bindingParamter(Parameter parameter, HttpServletRequest request) {
       MyRequstParam myRequstParam = parameter.getAnnotation(MyRequstParam.class);
       //获得注解的value值
       String MyRequstParamValue = myRequstParam.value();
       //获得参数的类名
       String parameterType = parameter.getType().getSimpleName();
       String parameter1 = request.getParameter(MyRequstParamValue);
       if (StringUtils.isEmpty(parameter1)) {
           throw new springmvcException("绑定参数异常");
       }
       //parameter1赋值
       if (parameterType.equals("String")) {
           return parameter1;
       } else if (parameterType.equals("Integer") || parameterType.equals("int")) {
         Integer binddingParameter =  Integer.valueOf(parameter1);
         return binddingParameter;
       }
       return null;
   }

}
package spring.springmvc;

import lombok.extern.slf4j.Slf4j;
import spring.Utils.AnnotationUtils;
import spring.Utils.ConvertUtis;
import spring.Utils.GetMethodName;
import spring.Utils.StringUtils;
import spring.annotation.MyModelAttribute;
import spring.exception.springmvcException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* @ClassName BindingByMyModelAttribute
* @Description 参数注解是MyModelAttribute时,绑定数据的类
* @Data 2018/7/4
* @Author xiao liang
*/
@Slf4j
public class BindingByMyModelAttribute implements   BindingParamter {
   @Override
   public Object bindingParamter(Parameter parameter, HttpServletRequest request) throws IllegalAccessException, InstantiationException, NoSuchMethodException {
       MyModelAttribute myModelAttribute = parameter.getAnnotation(MyModelAttribute.class);
       //获得参数的类名
       Class<?> aClass = parameter.getType();
       if (!AnnotationUtils.isEmpty(myModelAttribute)){
           if (!aClass.getSimpleName().equals(myModelAttribute.value())){
               throw new springmvcException("实体类绑定异常,请重新检查");
           }
       }
       Field[] fields = aClass.getDeclaredFields();
       Object object = aClass.newInstance();
       //遍历每个属性,用set注入将值注入到对象中
       for (Field field :
               fields) {
           //获得用户传来的值
           String parameter1 = request.getParameter(field.getName());
           if (!StringUtils.isEmpty(parameter1)){
               //将用户传过来的值转换成对应的参数类型
               Object setObject = ConvertUtis.convert(field.getType().getSimpleName(),parameter1);
               String methodName = GetMethodName.getSetMethodNameByField(field.getName());
               Method method = aClass.getMethod(methodName, field.getType());
               try {
                   //反射set注入
                   method.invoke(object,setObject);
               } catch (InvocationTargetException e) {
                   log.error("{}属性赋值异常",field.getName());
                   e.printStackTrace();
               }
           }
       }
       //返回对注入值后的对象
       return object;
   }
}

绑定完参数,就该返回ModelAndView了,

package spring.springmvc;

import lombok.Data;
/**
* @ClassName MyModelAndView
* @Description
* @Data 2018/7/4
* @Author xiao liang
*/
@Data
public class MyModelAndView {
   private String view;
   private MyModelMap modelMap;
   public MyModelAndView(String view) {
       this.view = view;
   }
}

view是视图名称,还有viewResolver,用来接收xml文件中定义的前缀和后缀。modelMap是数据域,最后渲染的时候要绑定到request中。

package spring.springmvc;

import lombok.Data;
/**
* @ClassName ViewResolver
* @Description 视图解析器 前缀和后缀
* @Data 2018/7/4
* @Author xiao liang
*/
@Data
public class ViewResolver {
   private String prefix = "";
   private String suffix = "";
}

最后的渲染类


package spring.springmvc;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;
/**
* @ClassName BindingRequestAndModel
* @Description
* @Data 2018/7/6
* @Author xiao liang
*/
public class BindingRequestAndModel {
   //遍历modelMap,然后将model中的数据绑定到requst中
   public static void bindingRequestAndModel(MyModelAndView myModelAndView, HttpServletRequest request) {
       MyModelMap myModelMap = myModelAndView.getModelMap();
       if (!myModelMap.isEmpty()){
           Set<Map.Entry<String, Object>> entries1 = myModelMap.entrySet();
           for (Map.Entry<String, Object> entryMap :
                   entries1) {
               String key = entryMap.getKey();
               Object value = entryMap.getValue();
               request.setAttribute(key,value);
           }
       }
   }
}

至此,最后在MyDispatcherServlet中用转发操作将试图返回。

request.getRequestDispatcher(resultAddress).forward(request,response);

我将此项目上传到了github,需要的童鞋可以自行下载。

https://github.com/836219171/MySSM

原文地址:https://blog.51cto.com/u_15127600/2757763

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


开发过程中是不可避免地会出现各种异常情况的,例如网络连接异常、数据格式异常、空指针异常等等。异常的出现可能导致程序的运行出现问题,甚至直接导致程序崩溃。因此,在开发过程中,合理处理异常、避免异常产生、以及对异常进行有效的调试是非常重要的。 对于异常的处理,一般分为两种方式: 编程式异常处理:是指在代
说明:使用注解方式实现AOP切面。 什么是AOP? 面向切面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能。 AOP底层使用动态代理。 AOP术语 连接点
Spring MVC中的拦截器是一种可以在请求处理过程中对请求进行拦截和处理的机制。 拦截器可以用于执行一些公共的操作,例如日志记录、权限验证、数据转换等。在Spring MVC中,可以通过实现HandlerInterceptor接口来创建自定义的拦截器,并通过配置来指定拦截器的应用范围和顺序。 S
在 JavaWeb 中,共享域指的是在 Servlet 中存储数据,以便在同一 Web 应用程序的多个组件中进行共享和访问。常见的共享域有四种:ServletContext、HttpSession、HttpServletRequest、PageContext。 ServletContext 共享域:
文件上传 说明: 使用maven构建web工程。 使用Thymeleaf技术进行服务器页面渲染。 使用ResponseEntity实现下载文件的功能。 @Controller public class FileDownloadAndUpload { @GetMapping(&quot;/file/d
创建初始化类,替换web.xml 在Servlet3.0环境中,Web容器(Tomcat)会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringS
在 Web 应用的三层架构中,确保在表述层(Presentation Layer)对数据进行检查和校验是非常重要的。正确的数据校验可以确保业务逻辑层(Business Logic Layer)基于有效和合法的数据进行处理,同时将错误的数据隔离在业务逻辑层之外。这有助于提高系统的健壮性、安全性和可维护
什么是事务? 事务(Transaction)是数据库操作最基本单元,逻辑上一组操作,要么都成功,要么都失败,如果操作之间有一个失败所有操作都失败 。 事务四个特性(ACID) 原子性 一组操作要么都成功,要么都失败。 一致性 一组数据从事务1合法状态转为事务2的另一种合法状态,就是一致。 隔离性 事
什么是JdbcTemplate? Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作。 准备工作 引入jdbcTemplate的相关依赖: 案例实操 创建jdbc.properties文件,配置数据库信息 jdbc.driver=com.mysql.cj.
SpringMVC1.MVC架构MVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范是将业务逻辑、数据、显示分离的方法来写代码MVC主要作用是:降低了视图和业务逻辑之间的双向耦合MVC是一个架构模型,不是一种设计模式。1.model(模型)数据模型,提供要展示的数据,因此包
SpringMVC学习笔记1.SpringMVC应用1.1SpringMVC简介​SpringMVC全名叫SpringWebMVC,是⼀种基于Java的实现MVC设计模型的请求驱动类型的轻量级Web框架,属于SpringFrameWork的后续产品。​MVC全名是ModelViewController,是模型(model)-视图(view)-控制器(co
11.1数据回显基本用法数据回显就是当用户数据提交失败时,自动填充好已经输入的数据。一般来说,如果使用Ajax来做数据提交,基本上是没有数据回显这个需求的,但是如果是通过表单做数据提交,那么数据回显就非常有必要了。11.1.1简单数据类型简单数据类型,实际上框架在这里没有
一、SpringMVC简介1、SpringMVC中重要组件DispatcherServlet:前端控制器,接收所有请求(如果配置/不包含jsp)HandlerMapping:解析请求格式的.判断希望要执行哪个具体的方法.HandlerAdapter:负责调用具体的方法.ViewResovler:视图解析器.解析结果,准备跳转到具体的物
1.它们主要负责的模块Spring主要应用于业务逻辑层。SpringMVC主要应用于表现层。MyBatis主要应用于持久层。2.它们的核心Spring有三大核心,分别是IOC(控制反转),DI(依赖注入)和AOP(面向切面编程)。SpringMVC的核心是DispatcherServlet(前端控制器)。MyBatis的核心是ORM(对
3.注解开发Springmvc1.使用注解开发要注意开启注解支持,2.注解简化了,处理映射器和处理适配器,只用去管视图解析器即可案例代码:1.web.xml,基本不变可以直接拿去用<!--调用DispatcherServlet--><servlet><servlet-name>springmvc</servlet-name>
拦截器概述SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。**过滤器与拦截器的区别:**拦截器是AOP思想的具体应用。过滤器servlet规范中的一部分,任何javaweb工程都可以使用
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="
学习内容:1、SSH&SSM2、Spring3、Struts2&SpringMVC4、Hibernate&MyBatis学习产出:1.SSH和SSM都是有Spring框架的,他们两个差不多。2.Spring分为四个模块,持久层,表示层,检测层,还有核心层,核心层分为2个关键核心功能。分别为,控制反转(IOC),依赖注入(DI),和面向切面编程
一、SpringMVC项目无法引入js,css的问题具体原因是css和js等被SpringMVC拦截了:解决方案:在spring-mvc.xml中配置<mvc:default-servlet-handler/><?xmlversion="1.0"encoding="UTF-8"?><beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
开发环境:Eclipse/MyEclipse、Tomcat8、Jdk1.8数据库:MySQL前端:JavaScript、jQuery、bootstrap4、particles.js后端:maven、SpringMVC、MyBatis、ajax、mysql读写分离、mybatis分页适用于:课程设计,毕业设计,学习等等系统介绍