ssm-03-spring-mvc-01-introduction

ssm-03-spring-mvc-01-introduction

MVC框架简介

在学习Spring MVC前,先来看看MVC框架。在经典的MVC模式中,M(Mode)指业务模型,V(View)指用户页面,C(Controller)指控制器,使用MVC的目的是让 M和V的代码实现解耦,从而使一个程序可以有不同的表现形式。
V(View):指用户看到并与之交互的界面;
M(Mode):指业务规则,返回了V视图所需的数据;
C(Controller):接受用户输入调用对应M模型处理业务,并返回对应V视图。

Spring MVC

通过Spring思想,将Web MVC整合,具有高度可配置等特点。随着前后端分离思想的推出,越来越多的企业已将V(View)由传统的JSP转向新一代的前端框架,如 VUE。下面通过简单的入门例子开始认识:

  1. 创建工程模块:


  2. 此时的干净工程目录结构如下:

  3. 接下来需要将工程改造-添加框架支持:

  4. 选择Spring MVCMaven

  5. 此时的工程目录结构如下:

  6. 配置pom文件:


  7. 由于maven版本的原因,子模块pom配置用统一的version时,可能会包红线提示:Properties in parent definition are prohibited.
    不过不影响工程的执行,如果有强迫症看不下去,可以升级maven版本,或者将父模块和子模块中的"version"改为"revision"。
  8. 修改web.xml:

  9. 在web.xml中,idea会自动为我们配置dispatcher的初始化参数:contextConfigLocation, 其值为:/WEB-INF/applicationContext.xml,接下来会对其进行配置
  10. 配置applicationContext.xml:

  11. <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
                   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">
        <!--自动扫描spring注解的组件,避免臃肿的bean配置-->
                <!--注解组件包括:@Component, @Repository, @Service, @Controller, @RestController, @ControllerAdvice, @Configuration-->
                <!--base-package:包含有注解组件的包名-->
        <context:component-scan base-package="com.zx.demo"/>
                <!--注解驱动,spring mvc专属配置,主要注册了dispatcher所需的RequestMappingHandlerMapping和RequestMappingHandlerAdapter-->
        <mvc:annotation-driven/>
    </beans>
  12. 创建Controller:

  13. import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    //@Controller配置声明的组件会被Spring自动装配
    @Controller
    public class TestController {
        //@RequestMapping注解对应:RequestMappingHandlerMapping
        @RequestMapping("/hello")
        //@ResponseBody注解表示可以直接向前端返回java对象
        @ResponseBody
        public String test() {
            //返回字符串
            return "Hello world.";
        }
    }
  14. 部署到tomcat并运行,浏览器中进行验证:

posted @ 2021-12-13 17:29  zhoux_top  阅读(343)  评论(0编辑  收藏  举报