zoukankan      html  css  js  c++  java
  • 第一个SpringMVC

    官方文档:https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc

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

    Spring MVC的特点

    1. 轻量级,简单易学

    2. 高效 , 基于请求响应的MVC框架

    3. 与Spring兼容性好,无缝结合

    4. 约定优于配置

    5. 功能强大:RESTful、数据验证、格式化、本地化、主题等

    6. 简洁灵活

      Spring的web框架围绕DispatcherServlet [ 调度Servlet ] 设计

    MVC模式

    Model(模型):数据模型,提供要展示的数据,因此包含数据和行为,可以认为是领域模型或JavaBean组件(包含数据和行为),不过现在一般都分离开来:Value Object(数据Dao) 和 服务层(行为Service)。也就是模型提供了模型数据查询和模型数据的状态更新等功能,包括数据和业务。

    View(视图):负责进行模型的展示,一般就是我们见到的用户界面,客户想看到的东西。

    Controller(控制器):接收用户请求,委托给模型进行处理(状态改变),处理完毕后把返回的模型数据返回给视图,由视图负责展示。也就是说控制器做了个调度员的工作。

    搭建XML版 SpringMVC Demo

    1.首先建一个Maven项目,并删掉项目中的src文件夹,作为父项目

    image-20210623215630576

    image-20210623220044159

    image-20210623220124090

    2.在父项目里面新建一个Maven项目作为子项目

    image-20210623220155415

    3.创建好之后在模块上右键添加add framework support ,钩选WEB支持即可

    image-20210623220232591

    image-20210623220319810

    这时候出现了一个小蓝点,成功

    image-20210623220425379

    4.在父项目的pom.xml中添加依赖

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    

    5.添加依赖之后,配置web.xml,注入dispatcherServlet,这是Spring MVC的核心,请求分发器

    <?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">
    
        <!--1.注册DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <!--启动级别-1-->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <!--/ 匹配所有的请求;(不包括.jsp)-->
        <!--/* 匹配所有的请求;(包括.jsp)-->
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    

    6.还需要创建一个配置文件springmvc-servlet.xml,放在src/main/resources目录下

    <?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
           http://www.springframework.org/schema/beans/spring-beans.xsd">
        
      <!--处理映射器-->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    
    <!--处理器适配器-->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
        <!--视图解析器:DispatcherServlet给他的ModelAndView-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
            <!--前缀-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--后缀-->
            <property name="suffix" value=".jsp"/>
        </bean>
        <bean id="/hello" class="com.ylc.Controller.HelloController"/>
    </beans>
    

    7.添加一个控制器HelloController,在src/main/java/com.ylc.Controller目录下

    package com.ylc.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 {
    
        @Override
        public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
            //ModelAndView 模型和视图
            ModelAndView mv = new ModelAndView();
    
            //封装对象,放在ModelAndView中。Model
            mv.addObject("msg","HelloSpringMVC!");
            //封装要跳转的视图,放在ModelAndView中
            mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
            return mv;
        }
    }
    

    然后在WEB-INF文件夹下新建一个jsp文件夹,里面新建一个hello.jsp页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <h1>${msg}</h1>
    </body>
    </html>
    

    8.配置Tomcat,请求路径/代表直接请求http://localhost:8080

    image-20210623221918820

    9.最后一步,不配置会有404错误

    在idea,File的project structure选项中,WEB-INF缺失lib文件夹,以及jar包

    image-20210623222128515

    image-20210623222313891

    image-20210623222600585

    10.项目运行,默认访问

    image-20210623222638204

    访问Hello

    image-20210623230202457

    用户发起一个请求,先从DispatcherServlet绑定的配置文件找到springmvc-servlet.xml,再通过处理器映射器找到/hello页面,再通过处理器适配器找到HelloController,Controller处理完之后返回一个

    ModelAndView交给视图解析器InternalResourceViewResolver,然后视图解析器返回DispatcherServlet,最后用户展示的页面就是拼接完成的。

    搭建最终版注解 SpringMVC Demo

    建一个web项目

    新建一个项目,同样模块上右键添加add framework support ,钩选WEB支持即可

    image-20210624222128885

    在idea,File的project structure选项中,WEB-INF添加缺失lib文件夹,以及jar包image-20210624222640348

    导入jar包

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</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>
    

    配置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">
        <!--1.注册DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <!--启动级别-1-->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <!--/ 匹配所有的请求;(不包括.jsp)-->
        <!--/* 匹配所有的请求;(包括.jsp)-->
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    

    在pom.xml中加入静态资源配置

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

    添加Spring MVC配置文件

    在src/main/resources目录下,新建一个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
           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">
    
        <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
        <context:component-scan base-package="com.ylc.Controller"/>
        <!-- 让Spring MVC不处理静态资源 -->
        <mvc:default-servlet-handler />
        <!--
        支持mvc注解驱动
            在spring中一般采用@RequestMapping注解来完成映射关系
            要想使@RequestMapping注解生效
            必须向上下文中注册DefaultAnnotationHandlerMapping
            和一个AnnotationMethodHandlerAdapter实例
            这两个实例分别在类级别和方法级别处理。
            而annotation-driven配置帮助我们自动完成上述两个实例的注入。
         -->
        <mvc:annotation-driven />
    
        <!-- 视图解析器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              id="internalResourceViewResolver">
            <!-- 前缀 -->
            <property name="prefix" value="/WEB-INF/jsp/" />
            <!-- 后缀 -->
            <property name="suffix" value=".jsp" />
        </bean>
    
    </beans>
    

    创建Controller类

    @Controller
    public class HelloController {
        //访问地址:项目名+HelloController/hello
        @RequestMapping("/hello")
        public  String hello(Model model)
        {
            //封装数据 向模型添加值
            model.addAttribute("msg","Hello SpringMVC!");
            //web-inf/jsp/hello.jsp
            return  "hello";//会被视图解析器处理
        }
    }
    

    image-20210624232341402

    测试

    image-20210624231713374

    使用springMVC必须配置的三大件:处理器映射器、处理器适配器、视图解析器

    通常,我们只需要手动配置视图解析器,而处理器映射器处理器适配器只需要开启注解驱动即可,而省去了大段的xml配置

  • 相关阅读:
    Atitit.数据库存储引擎的原理与attilax 总结
    Atitit.数据库存储引擎的原理与attilax 总结
    atitit.guice3 绑定方式打总结生成非单例对象toInstance toProvider区别 v2 pb29
    atitit.guice3 绑定方式打总结生成非单例对象toInstance toProvider区别 v2 pb29
    atitit.项目设计模式---ioc attilax总结v4 q11
    atitit.项目设计模式---ioc attilax总结v4 q11
    Atitit.attilax的 case list 项目经验 案例列表
    Atitit.attilax的 case list 项目经验 案例列表
    Atitit.python web环境的配置 attilax 总结
    Atitit.python web环境的配置 attilax 总结
  • 原文地址:https://www.cnblogs.com/cg-ww/p/14929112.html
Copyright © 2011-2022 走看看