SMVC1:SpringMVC简介、案例及原理的简单说明

1.简介

1.1 MVC

MVC: 模型(dao、service)、视图(jsp)、控制器(servlet),mvc不是设计模式,而是一种架构模式。当然,在早期的web开发中,都是使用的Model1,在Model1中,主要分为两层:视图层与模型层。

1.2 SpringMVC

定义: SpringMVC是基于java实习MVC的轻量级Web框架。

特点: 1.轻量级,简单易学。2.高效,基于请求相应的MVC框架。3.与Spring兼容较好,无缝衔接。4.约定大于配置。5.功能强大:RESTful风格(不使用问号传参,使用斜线分割)、数据验证、格式化、本地化、主题等。6.简洁灵活。

1.3 SpringMVC案例

Maven依赖:

dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
         <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

资源无法正确导出:

<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>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         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">

    <!--        注册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>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--下面的配置内容是:/,而不是/*-->
        <url-pattern>/</url-pattern>
        
    </servlet-mapping>
</web-app>

提示: //* 的区别在于,前者只能匹配请求,不能匹配jsp,而后者不仅可以匹配请求,匹配jsp。

springmvc-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    
<!--        处理器映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    
    <!--        处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!--        视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--以下语句,是beanHandler的特有配置-->
    <bean id="/hello" class="com.yun.controller.HelloController"/>
</beans>

HelloController:

package com.yun.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

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


public class HelloController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();

        //数据封装
        mv.addObject("msg","HelloSpringMVC");
        
//        设置需要跳转的视图,hello等同于/web-inf/jsp/hello.jsp
        mv.setViewName("hello");
        return mv;
    }
}

hello.jsp:

<%--
  Created by IntelliJ IDEA.
  User: yun
  Date: 2021/9/22
  Time: 15:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

提示: URL栏中,直接进行访问hello即可,例如:http://localhost:8080/SpringMVC_01_servlet_war_exploded/hello。代码正常即可出现 HelloSpringMVC 字样的页面。如果没有代码错误,依旧运行失败,那么,则需要对项目的war包进行依赖导入: File-Project Structure-Artifacts ,选择当前的war包,并且在web-inf目录下创建lib目录。然后点击加号,选择 Library files ,并导入所有的依赖。

1.4 SpringMVC执行原理

在这里插入图片描述

提示: 视线表示的是Spring帮我们做的,而虚线表示的是需要自己去实现的部分。

过程:

1: DispatcherServlet表示前端控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接受请求,并拦截。

  • 访问地址为:http://localhost:8080/SpringMVC_01_servlet_war_exploded/hello,可分为三部分。
  • 第一部分,http://localhost:8080。这是域名服务器,也就是网址与端口
  • 第二部分,SpringMVC_01_servlet_war_exploded。这是部署在服务器上的web站点,也就是我们的项目名字。
  • 第三部分,hello。这是控制器,也就是我们写的Controller。

总结: 完整地说就是,请求了某服务器上某端口中的某站点的某个控制器。

2: HandlerMapping是处理器映射。主要是由DispathcerServlet来调用,然后HandlerMapping根据请求URL查找到Handler。也就是Spring-dao.xml文件中的这两句话在起作用:

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

<bean id="/hello" class="com.yun.controller.HelloController"/>

3: HandlerExecution表示具体的Handler,主要作用则是,根据URL查找控制器,如hello。

4: HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射。

5: HandlerAdapter表示处理器适配器,按照特定的规则去执行Handler(其实所谓特定规则,就是指这里有一个控制器,需要去执行控制器)。

6: 这一步,则是Handler让具体的Controller执行。

7: Controller将执行结果返回给HandlerAdapter,如ModelAndView。

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();

        mv.addObject("msg","HelloSpringMVC");
//        设置需要跳转的视图,hello等同于/web-inf/jsp/hello.jsp
        mv.setViewName("hello");
        return mv;
    }

8: HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet。

9: DispatcherServlet调用视图解析器(ViewResoler)来解析HandlerAdapter传递逻辑视图名。

10: 视图解析器将解析的逻辑视图名传递给DispatcherServlet。

11: DispatcherServlet根据视图解析器解析的视图结果,调用具体的视图。

12: 最终视图呈现给用户。

1.5 使用注解改造案例

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         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">

    <!--        注册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>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--下面的配置内容是:/,而不是/*-->
        <url-pattern>/</url-pattern>

    </servlet-mapping>
</web-app>

提示: 上述文件的配置基本是死的,而且只有一个DispatcherServlet的配置,主要内容则是: 注册Srpingmvc关联SpringMVC的配置文件设置启动级别Dispatcher映射

springmvc-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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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">

<!--    配置扫描器-->
    <context:component-scan base-package="com.yun.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>

提示: 由于使用注解进行开发,所以需要在SpringMVC的配置文件中,配置一个扫描器,用于 扫描特定包下的注解 。并且,由于很多静态资源是不用使用视图解析器的,所以配置了一个 静态资源过滤 器(我是这样叫的)。并且,处理控制器与处理适配器,都可以使用注解驱动进行配置。但是,视图解析器则是必须的。并且,使用注解之后, 请求与控制器之间的Bean,也不需要了 。本文件,在配置上,基本也是死的。

HelloController:

package com.yun.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 hello(Model model){
        model.addAttribute("msg","你好,这是SpringMVC");
        //这里返回的字符串,则是需要返回的前端页面的名字,
        return "helloPage";
    }
}

提示: @Controller 注解,就是告诉Spring这里是控制器,在Spring5中,也有讲过。除了控制层,其他层也有相应的注解:@Repository、@Service、@Component等 。而 @RequestMapping("/hello") 则是代替了原本 springmvc-servlet.xml 文件中的bean:

<bean id="/hello" class="com.yun.controller.HelloController"/>

如果请求存在多层级的情况,如:/hello/test。这时候需要在类上面也加上 @RequestMapping 注解。而 return “helloPage” 语句则是相当于 ModelAndView.setViewName(“hello”) 语句。

helloPage.jsp:

<%--
  Created by IntelliJ IDEA.
  User: yun
  Date: 2021/9/24
  Time: 14:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

提示: 前端文件并没有任何变化。如果上述代码完全正确,则需要查看项目war包是否拥有lib目录。如果没有,则需要对项目的war包进行依赖导入: File-Project Structure-Artifacts ,选择当前的war包,并且在web-inf目录下创建lib目录。然后点击加号,选择 Library files ,并导入所有的依赖。


罗素曾说过:生下来只是无知,并不愚蠢。愚蠢是后来的教育造成的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值