SpringMVC简介及第一个SpringMVC程序

SpringMVC简介及第一个SpringMVC程序

一、MVC

  • MVC : 模型、视图、控制器 , 是一种软件设计规范,而不是设计模式

  • 本质:将业务逻辑 ,数据 ,显示分离的方式来编写代码,从而实现前后端分离

  • Model:数据模型,提供要展示的数据,一般会把这两个分离开来,即数据Dao层,Service服务层

  • View:负责进行数据的渲染和展示,即客户端想要看到的东西

  • Controller:接收用户请求,交给Model处理,从Model更新后的数据或者结果,返回给前端,类似于一个调度员

  • web开发经历了两个时代,即Model1时代和Model2时代

  • Model1

    在早期的Web开发中,就是用的Model1模式,只有两层:视图层和模型层

在这里插入图片描述

​ 优点:架构简单,适合小型项目开发;

​ 缺点:JSP职责不单一 , 承受它不该承受的压力,不便于维护

  • Model2

    将项目分为三个模块:M:模型 V:视图 C :控制器

在这里插入图片描述

Model

​ 1.Dao:操作数据库

​ 2.Service:业务逻辑

​ 3.保存数据的更新状态

controller

​ 1.取得表单的数据

​ 2.调用业务的逻辑方法

​ 3.转向指定的页面

View

​ 显示页面

​ Model2优化了Model1时代的缺点,让所有层职责更加分明,降低了维护难度

二、SpringMVC

  • SpringMVC 是 Spring的一部分,是基于Java实现的MVC的轻量级Web框架

  • SpringMVC优点:

    • 趋势,使用的人多。

    • 简单,易学,轻量级

    • 高效,基于请求和响应的MVC框架

    • 约定优于配置

    • 功能强大:RestFul、数据验证、格式化{json}、主题,本地化、异常处理…

  • 官网详细介绍了Spring的web模块提供了大量独特的功能,包括:

    清晰的角色划分:控制器(controller)、验证器(validator)、 命令对象(command object)、表单对象(form object)、模型对象(model object)、 Servlet分发器(DispatcherServlet)、 处理器映射(handler mapping)、视图解析器(view resolver)等等。 每一个角色都可以由一个专门的对象(类)来实现。< Bean>

    强大而直接的配置方式:将框架类和应用程序类都能作为JavaBean配置,而且支持跨多个context 的引用。

    可适配、非侵入:可以根据不同的应用场景,选择合适的控制器子类 (simple型、command型、form型、wizard型、multi-action型或者自定义),而不是从单一控制器 (比如Action/ActionForm)继承。

    可重用的业务代码:可以使用现有的业务对象作为命令或表单对象,而不需要去扩展某个特定框架的基类。

    可定制的绑定(binding) 和验证(validation):比如将类型不匹配作为应用级的验证错误, 这可以保存错误的值。再比如本地化的日期和数字绑定等等。在其他某些框架中,你只能使用字符串表单对象, 需要手动解析它并转换到业务对象。

    可定制的handler mapping和view resolution:Spring提供从最简单的URL映射, 到复杂的、专用的定制策略。与某些web MVC框架强制开发人员使用单一特定技术相比,Spring显得更加灵活。

    灵活的model转换:在Springweb框架中,使用基于Map的 键/值对来达到轻易地与各种视图技术的集成。

    可定制的本地化和主题(theme)解析:支持在JSP中可选择地使用Spring标签库、支持JSTL、支持Velocity(不需要额外的中间层)等等。

    简单而强大的JSP标签库(Spring Tag Library):支持包括诸如数据绑定和主题(theme) 之类的许多功能。它提供在标记方面的最大灵活性。

    JSP表单标签库:在Spring2.0中引入的表单标签库,使得在JSP中编写 表单更加容易。

    Spring Bean的生命周期可以被限制在当前的HTTP Request或者HTTP Session。 准确的说,这并非Spring MVC框架本身特性,而应归属于Sping MVC使用的WebApplicationContext容器。

    正因为SpringMVC较Struct2好 , 简单 , 便捷 , 易学 , 天生和Spring无缝集成(使用SpringIoC和Aop) , 使用约定优于配置 . 能够进行简单的junit测试 . 支持Restful风格 .异常处理 , 本地化 , 国际化 , 数据验证 , 类型转换 , 拦截器 等等…所以我们要学习 .

    SpringMVC框架围绕着DispatcherServlet(Servlet请求分发器)设计

三、HelloSpringMVC

  1. 利用maven创建一个web项目

  2. 导包

    注意要在build标签中添加上resources标签象关内容,解决资源导出问题,否则项目在运行时可能资源文件找不到的异常

    <dependencies>
      <!--junit包单元测试-->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
      </dependency>
      <!-- Spring MVC 及 Spring系列包 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.24.RELEASE</version>
      </dependency>
      <!--jstl 和 jsp的包-->
    
      <!--Servlet核心-->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
      </dependency>
      <!-- JSTL -->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
      </dependency>
      
    </dependencies>
    
    
    <build>
        <!--解决资源导出问题-->
        <resources>
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>**/*.properties</include>
              <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
          </resource>
          <resource>
            <directory>src/main/resources</directory>
            <includes>
              <include>**/*.properties</include>
              <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
          </resource>
        </resources>
    </build>
    
  3. 在resources目录下配置SpringMVC核心配置文件

    注意配置文件命名为:xxx-servlet.xml

    <?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:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            https://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">
    
        <!--扫描指定包下的注解,让指定的类能够被IOC容器管理-->
        <!--使用注解方式必加-->
        <context:component-scan base-package="org.westos.controller"/>
    
        <!--静态资源过滤-->
        <!--使用注解时需要-->
        <mvc:default-servlet-handler/>
    
        <!--注解驱动 -->
        <mvc:annotation-driven/>
    
        <!--
        视图解析器
        所有方法都需要
        作用;方便统一管理
        -->
        <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
    </beans>
    
  4. 配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://java.sun.com/xml/ns/javaee"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
             id="WebApp_ID" version="3.0">
    
      <!--所有请求都会经过这个DispatcherServlet请求分发器-->
      <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--关联SpringMVC配置文件-->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--和服务器一起启动;
        load-on-startup,启动级别,数字越小级别越高!-->
        <load-on-startup>1</load-on-startup>
      </servlet>
    
    
      <!--
      /和/*的区别:
      < url-pattern > / </ url-pattern > 不会匹配到.jsp, 只针对我们编写的请求;
        即:.jsp不会进入spring的 DispatcherServlet类 。
      < url-pattern > /* </ url-pattern > 会匹配*.jsp,
        会出现返回jsp视图时再次进入spring的DispatcherServlet 类,导致找不到对应的controller所以报404错。
      -->
      <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    
    </web-app>
    
  5. 编写Controller类

    • 需要给类加注解 :@Controller , 可以让IOC容器管理 , 等价于Bean
    • 请求映射的路径 :@RequestMapping (“路径”),如果类上有就先写类的,在写方法的;
    • Model :模型传递参数
    • return “hello”; 它会去视图解析中拼接前缀和后缀来找到对应的视图
    package org.westos.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HelloController {
        //请求映射("路径")
        @RequestMapping("/hello")
        public String hi(Model model){
            model.addAttribute("msg","Hello,SpringMVC");
            return "hello"; //返回给视图解析器拼装后为WEB-INF/jsp/hello.jsp
        }
    }
    
  6. 视图层

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>SpringMVC</title>
    </head>
    <body>
        ${msg}
    </body>
    </html>
    
  7. 配置Tomcat即可成功测试
    在这里插入图片描述

四、使用URL对应Bean的方式配置核心文件

上面的案例使用的是注解方式,我们还可以使用URL对应Bean方式进行开发,使用此方法SpringMVC的配置文件中不再需要注解驱动等内容,具体如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd

    <!--URL对应Bean-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean id="/hello2" class="org.westos.controller.HelloController2"/>


    <!--
    视图解析器
    所有方法都需要
    作用;方便统一管理
    -->
    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

控制类使用的不是Model对象传递参数,而是ModelAndView的对象进行参数传递,如下

package org.westos.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class HelloController2 {
    @RequestMapping("/hello2")
    public ModelAndView hello(HttpServletRequest req, HttpServletResponse resp){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","Hello SpringMVC2");
        mv.setViewName("hello");
        return mv;
    }
}

注意@RequestMapping("/hello2")要与配置文件的

<bean id="/hello2" class="org.westos.controller.HelloController2"/>相匹配
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值