java 底层运行_SpringMVC底层执行流程及原理解析

一个简单的HelloSpringMVC程序

先在web,xml中注册一个前端控制器(DispatcherServlet)

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

springmvc

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:springmvc-servlet.xml

1

springmvc

/

配置文件(springmvc-servlet.xml)

HandlerMapper是处理器映射器-->根据请求的地址去找处理器(如案例中的"/hello")

HandlerAdapter是处理器适配器-->找到处理器后根据id去适配对应的controller(如适配到案例中的HelloController),controller会返回ModelAndView及其前端数据

ViewResolver是视图解析器,其作用为:

1.获取到ModelAndView中的数据

2.解析视图名称

3.拼接视图名称

4.数据渲染

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

controller层:

实现Controller接口,重写内部方法(一般不会使用,这是底层原理)

ModelAndView是模型、视图

public class HelloController implements Controller {

@Override

public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

ModelAndView mv = new ModelAndView();

mv.addObject("msg","HelloSpringMVC!");

mv.setViewName("test");

return mv;

}

}

底层流程图

实线是SpringMVC已经帮你实现好了,虚线是需要自己手动

984e3003ad728db1cbcc498b54a0e243.png

以上仅是说明底层执行原理,实际开发并不会这样去使用!

在实际开发中SpringMVC推荐使用注解的方式

在注解开发中,不需要我们去配置处理器适配器和处理器映射器。

web.xml中只需配置DispatcherServlet前端控制器

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

SpringMVC

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:springmvc-servlet.xml

1

SpringMVC

/

在springmvc-servlet.xml中配置视图解析器等

/*组件扫描,用于扫描controller下的包*/

/*静态资源过滤*/

/*这个就帮助我们配置了映射器以及适配器*/

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/mvc

https://www.springframework.org/schema/mvc/spring-mvc.xsd">

contorller

@Controller    //说明这类被Spring托管了

@RequestMapping("/hello")

public class HelloController {

@RequestMapping("/h1")   //这个注解会执行视图解析器

public String hello(Model model){

model.addAttribute("msg","helloSpringMVCAnnotation");

return "hello";

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值