SpringMVC执行流程

Spring MVC 请求处理流程

在这里插入图片描述
流程说明:

  • 第⼀步:⽤户发送请求⾄前端控制器DispatcherServlet
  • 第⼆步:DispatcherServlet收到请求调⽤HandlerMapping处理器映射器
  • 第三步:处理器映射器根据请求Url找到具体的Handler(后端控制器),⽣成处理器对象及处理器拦截器(如果 有则⽣成)⼀并返回DispatcherServlet
  • 第四步:DispatcherServlet调⽤HandlerAdapter处理器适配器去调⽤Handler
  • 第五步:处理器适配器执⾏Handler
  • 第六步:Handler执⾏完成给处理器适配器返回ModelAndView
  • 第七步:处理器适配器向前端控制器返回 ModelAndView,ModelAndView 是SpringMVC 框架的⼀个底层对 象,包括 Model 和 View
  • 第⼋步:前端控制器请求视图解析器去进⾏视图解析,根据逻辑视图名来解析真正的视图。
  • 第九步:视图解析器向前端控制器返回View
  • 第⼗步:前端控制器进⾏视图渲染,就是将模型数据(在 ModelAndView 对象中)填充到 request - 域
  • 第⼗⼀步:前端控制器向⽤户响应结果

⼿写 MVC 框架

在这里插入图片描述
手写MVC框架之注解开发:

  • LagouAutowired
import java.lang.annotation.*;

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouAutowired {
    String value() default "";
}
  • LagouController
import java.lang.annotation.*;

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouController {
    String value() default "";
}
  • LagouService
import java.lang.annotation.*;

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouService {
    String value() default "";
}
  • LagouRequestMapping
import java.lang.annotation.*;

@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouRequestMapping {
    String value() default "";
}
  • Pojo类Handler
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 封装handler⽅法相关的信息
 */
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<>();
    }

    public Object getController() {
        return controller;
    }

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

    public Method getMethod() {
        return method;
    }

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

    public Pattern getPattern() {
        return pattern;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Map<String, Integer> getParamIndexMapping() {
        return paramIndexMapping;
    }

    public void setParamIndexMapping(Map<String, Integer> paramIndexMapping) {
        this.paramIndexMapping = paramIndexMapping;
    }
}
  • 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>lgoumvc</servlet-name>
    <servlet-class>com.lagou.edu.mvcframework.servlet.LgDispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>springmvc.properties</param-value>
    </init-param>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>lgoumvc</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>
  • springmvc.xml
scanPackage=com.lagou.demo
  • LgDispatcherServlet
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouController;
import com.lagou.edu.mvcframework.annotations.LagouRequestMapping;
import com.lagou.edu.mvcframework.annotations.LagouService;
import com.lagou.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;
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.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LgDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();
    private List<String> classNames = new ArrayList<>(); // 缓存扫描到的类的全限定类名
    // ioc容器
    private Map<String,Object> ioc = new HashMap<String,Object>();
    // handlerMapping
    // private Map<String,Method> handlerMapping = now HashMap<>();
    // 存储url和Method之间的映射关系
    private List<Handler> handlerMapping = new ArrayList<>();

    /**
     *  初始化方法
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1. 加载配置⽂件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 2. 扫描相关的类,扫描注解
        doScan(properties.getProperty("scanPackage"));
        // 3. 初始化bean对象(实现ioc容器,基于注解)
        doInstance();
        // 4. 实现依赖注⼊ ->属性赋值
        doAutoWired();
        // 5. 构造⼀个HandlerMapping处理器映射器,将配置好的url和Method建⽴映射关系
        initHandlerMapping();


        System.out.println("lagou mvc 初始化完成....");
        // 等待请求进⼊,处理请求
    }

    /**
     * 最关键的环节:构造⼀个HandlerMapping处理器映射器
     * ⽬的:将url和method建⽴关联
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            // 获取ioc中当前遍历的对象的class类型
            Class<?> aClass = entry.getValue().getClass();
            // 只处理controller层,不处理service层
            if (!aClass.isAnnotationPresent(LagouController.class)) {
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(LagouRequestMapping.class)) {
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value(); // 等同于  /demo
            }
            // 获取⽅法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i]; // ⽅法没有标识LagouRequestMapping,就不处理
                if (!method.isAnnotationPresent(LagouRequestMapping.class)) {
                    continue;
                }
                // 如果标识,就处理
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation.value(); // /query
                String url = baseUrl + methodUrl; // 计算出来的url /demo/query

                // 把method所有信息及url封装为⼀个Handler
                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
                // 计算⽅法的参数位置信息
                // query(HttpServletRequest request, HttpServletResponse response,String name)
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        // 如果是request和response对象,那么参数名称写HttpServletRequest和HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getName(), j); // <name,2>
                    }
                }
                // 建⽴url和method之间的映射关系(map缓存起来)
                handlerMapping.add(handler);
            }
        }
    }

    /**
     * 实现依赖注⼊
     */
    private void doAutoWired() {
        if (ioc.isEmpty()) {
            return;
        }
        // 有对象,再进⾏依赖注⼊处理
        // 遍历ioc中所有对象,查看对象中的字段,是否有@LagouAutowired注解,如果有需要维护依赖注⼊关系
        for(Map.Entry<String,Object> entry: ioc.entrySet()) {
            // 获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            // 遍历判断处理
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                // @LagouAutowired private IDemoService demoService;
                if (!declaredField.isAnnotationPresent(LagouAutowired.class)) {
                    continue;
                }
                // 有该注解
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                String beanName = annotation.value();
                // 需要注⼊的bean的id
                if("".equals(beanName.trim())) {
                    // 没有配置具体的bean id,那就需要根据当前字段类型注⼊(接⼝注⼊)IDemoService
                    beanName = declaredField.getType().getName();
                }
                // 开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * ioc容器
     * 基于classNames缓存的类的全限定类名,以及反射技术,完成对象创建和管理
     */
    private void doInstance() {
        if (classNames.size() == 0) return;
        try {
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i); // com.lagou.demo.controller.DemoController
                // 反射
                Class<?> aClass = Class.forName(className);
                // 区分controller,区分service
                if(aClass.isAnnotationPresent(LagouController.class)) {
                    // controller的id此处不做过多处理,不取value了,就拿类的⾸字⺟⼩写作为id,保存到ioc中
                    String simpleName = aClass.getSimpleName();// DemoController
                    String lowerFirstSimpleName = lowerFirst(simpleName); // demoController
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                } else if (aClass.isAnnotationPresent(LagouService.class)) {
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    //获取注解value值
                    String beanName = annotation.value();
                    // 如果指定了id,就以指定的为准
                    if(!"".equals(beanName.trim())) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        // 如果没有指定,就以类名⾸字⺟⼩写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName, aClass.newInstance());
                    }
                    // service层往往是有接⼝的,⾯向接⼝开发,此时再以接⼝名为id,放⼊⼀份对象到ioc中,便于后期根据接⼝类型注⼊
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        // 以接⼝的全限定类名作为id放⼊
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ⾸字⺟⼩写⽅法
     * @param str
     * @return
     */
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    /**
     * 扫描类
     * scanPackage: com.lagou.demo package----> 磁盘上的⽂件夹(File) com/lagou/demo
     * @param scanPackage
     */
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                // ⼦package
                // 递归
                doScan(scanPackage + "." + file.getName()); // com.lagou.demo.controller
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 加载配置⽂件
      * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收处理请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * 接收处理请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求:根据url,找到对应的Method⽅法,进⾏调⽤
        // 获取uri
        //String requestURI = req.getRequestURI();
        //Method method = handlerMapping.get(requestURI);
        // 获取到⼀个反射的⽅法
        // 反射调⽤,需要传⼊对象,需要传⼊参数,此处无法完成调⽤,没有把对象缓存起来,也没有参数!!!!改造initHandlerMapping();
        // method.invoke()
        // 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))


        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }
        // 参数绑定
        // 获取所有参数类型数组,这个数组的⻓度就是我们最后要传⼊的args数组的⻓度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        // 根据上述数组⻓度创建⼀个新的数组(参数数组,是要传⼊反射调⽤的)
        Object[] paraValues = new Object[parameterTypes.length];
        // 以下就是为了向参数数组中塞值,⽽且还得保证参数的顺序和⽅法中形参顺序⼀致
        Map<String, String[]> parameterMap = req.getParameterMap();

        // 遍历request中所有参数 (填充除了request,response之外的参数)
        for(Map.Entry<String,String[]> param: parameterMap.entrySet()) {
            // name=1&name=2 name [1,2]
            String value = StringUtils.join(param.getValue(), ","); // 如同 1,2
            // 如果参数和⽅法中的参数匹配上了,填充数据
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }
            // ⽅法形参确实有该参数,找到它的索引位置,对应的把参数值放⼊paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());
            //name在第 2 个位置
            paraValues[index] = value;
            // 把前台传递过来的参数值填充到对应的位置去
        }
        //request,response对象直接取出就可以
        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());// 0
        paraValues[requestIndex] = req;
        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());// 1
        paraValues[responseIndex] = resp;

        // 最终调⽤handler的method属性
        try {
            // Pojo类Handler
            handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据请求request获取对应的Handler对象
     * @param req
     * @return
     */
    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

}

Spring MVC请求参数绑定

  • 默认⽀持 Servlet API 作为⽅法参数

  • 绑定简单类型参数
    简单数据类型:⼋种基本数据类型及其包装类型
    参数类型推荐使⽤包装数据类型,因为基础数据类型不可以为null
    整型:Integer、int
    字符串:String
    单精度:Float、float
    双精度:Double、double
    布尔型:Boolean、boolean
    说明:对于布尔类型的参数,请求的参数值为true或false。或者1或0

/*
 * SpringMVC 接收简单数据类型参数  url:/demo/handle03?id=1
 *
 * 注意:接收简单数据类型参数,直接在handler方法的形参中声明即可,框架会取出参数值然后绑定到对应参数上
 * 要求:传递的参数名和声明的形参名称保持一致
 */
@RequestMapping("/handle03")
public ModelAndView handle03(@RequestParam("ids") Integer id,Boolean flag) {

    Date date = new Date();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("date",date);
    modelAndView.setViewName("success");
    return modelAndView;
}

  • 绑定Pojo包装对象参数
/*
 * SpringMVC接收pojo类型参数  url:/demo/handle04?id=1&username=zhangsan
 *
 * 接收pojo类型参数,直接形参声明即可,类型就是Pojo的类型,形参名无所谓
 * 但是要求传递的参数名必须和Pojo的属性名保持一致
 */
@RequestMapping("/handle04")
public ModelAndView handle04(User user) {

    Date date = new Date();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("date",date);
    modelAndView.setViewName("success");
    return modelAndView;
}
  • 绑定日期类型参数(需要配置自定义类型转换器)

1.DateConverter.java:

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  自定义类型转换器
 * S:source,源类型
 * T:target:目标类型
 */
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        // 完成字符串向日期的转换
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date parse = simpleDateFormat.parse(source);
            return parse;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }
}

2.springmvc.xml中:

<!--注册自定义类型转换器-->
<bean id="conversionServiceBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.lagou.edu.converter.DateConverter"></bean>
        </set>
    </property>
</bean>

3.controller类中的方法使用:

/**
* 绑定日期类型参数
* 定义一个SpringMVC的类型转换器  接口,扩展实现接口接口,注册你的实现
* @param birthday
* @return
*/
@RequestMapping("/handle06")
public ModelAndView handle06(Date birthday) {
   Date date = new Date();ModelAndView modelAndView = new ModelAndView();
   modelAndView.addObject("date",date);
   modelAndView.setViewName("success");
   return modelAndView;
}
  • Restful 风格请求
 /*
* restful  get  /demo/handle/15/lisi
 */
@RequestMapping(value = "/handle/{id}/{name}",method = {RequestMethod.GET})
public ModelAndView handlePut(@PathVariable("id") Integer id,@PathVariable("name") String username) {

    Date date = new Date();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("date",date);
    modelAndView.setViewName("success");
    return modelAndView;
}

  • Ajax Json交互

1)前端到后台:前端ajax发送json格式字符串,后台直接接收为pojo参数,使⽤注解@RequstBody
2)后台到前端:后台直接返回pojo对象,前端直接接收为json对象或者字符串,使⽤注解@ResponseBody

@RequestMapping("/handle07")
// 添加@ResponseBody之后,不再走视图解析器那个流程,而是等同于response直接输出数据

public @ResponseBody User handle07(@RequestBody User user) {

    // 业务逻辑处理,修改name为张三丰
    user.setName("张三丰");
    return user;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值