第一个SpringMVC

简介: 第一个SpringMVC

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

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文件夹,作为父项目

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

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

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

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

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

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

10.项目运行,默认访问

访问Hello

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

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

搭建最终版注解 SpringMVC Demo

建一个web项目

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

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

导入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";//会被视图解析器处理
    }
}

测试

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

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

相关文章
|
7月前
|
Java 编译器 Windows
JDK 21安装教程:Windows系统一步到位(附常见问题解决)
本文详解Windows下JDK 21安装全流程:从下载、管理员运行、路径选择到环境变量验证,并汇总权限不足、命令未识别、版本冲突等常见问题及解决方案,助新手快速完成Java开发环境搭建。
2422 0
|
7月前
|
人工智能 自然语言处理 算法
2026年运营岗正在分层:懂AI应用的运营和只会排期的运营差距有多大
2026年运营岗加速分层:一类陷于排期催单,另一类借AI做用户洞察、内容生成、活动复盘与工作流提效。效率、价值与晋升差距显著拉大。真正稀缺的是“AI协作力”——懂Prompt、会搭工作流、能落地RAG/Agent。推荐考取CAIE注册人工智能工程师(Level I),零基础友好、企业认可度高,助运营从执行者跃升为业务增长关键接口人。
2026年运营岗正在分层:懂AI应用的运营和只会排期的运营差距有多大
|
5月前
|
弹性计算 人工智能 小程序
阿里云轻量应用服务器怎么样?全新升级200Mbps公网峰值带宽,不限流量!
阿里云轻量应用服务器标称200Mbps“峰值带宽”,实为共享型弹性带宽:空闲时段(如凌晨)上传/下载可达160–176Mbps,但高峰时段常降至20–50Mbps;非固定保障,不适用于直播、电商秒杀等强稳定性场景,更适合博客、小程序后端、开发测试等轻量级应用。阿里云轻量应用服务器官网:https://t.aliyun.com/U/dwftch
|
6月前
|
人工智能 运维 监控
阿里云百炼大模型平台是什么解析:核心功能、价格体系与配置指南
阿里云百炼大模型平台(Model Studio)是阿里云打造的一站式大模型开发与应用服务平台,面向开发者、企业与业务人员提供全链路AI能力支持。它集成通义千问全系模型与主流第三方大模型,兼容OpenAI API标准,兼顾低代码可视化操作与高代码深度开发,覆盖模型调用、微调训练、知识库构建、智能体开发、应用部署与运维全流程,是企业与个人快速落地AI应用、降低大模型使用门槛的核心工具。
1458 2
|
6月前
|
人工智能 监控 安全
AI Agent进入生产环境前,企业安全必须回答的七个问题
本文以闲鱼AI误将用户照片自动上架事件为引,剖析Agent系统与传统LLM的本质风险差异,指出其“操作半径×不可逆程度”的放大效应。结合《2026国际AI安全报告》及多项前沿研究,提出覆盖权限控制、强制确认、运行监控、安全评估与紧急关停的五层企业级治理框架,强调Agent安全是需持续运营的工程能力,而非一次性技术问题。
519 0
|
负载均衡 Java Nacos
SpringCloud基础2——Nacos配置、Feign、Gateway
nacos配置管理、Feign远程调用、Gateway服务网关
SpringCloud基础2——Nacos配置、Feign、Gateway
|
网络协议 关系型数据库 Linux
手把手教你使用phpstudy本地快速搭建网站,并外网访问【无公网IP】
手把手教你使用phpstudy本地快速搭建网站,并外网访问【无公网IP】
|
人工智能
如何利用ai快速写汇报、方案、总结。
本文介绍了一套与AI有效沟通的方法,以生成符合需求的文章。通过构建【角色+背景+任务+要求】的提示词框架,并辅以调试优化,可显著提升AI输出内容的质量。角色设定应包括单位、身份与能力;背景描述需涵盖宏观、微观及受众层面;任务需界定清晰,并可细分为文本输出或立意构思;要求则涉及语言风格、字数限制及内容结构。通过不断调试,最终产出满足期望的文章。
2318 6
|
Java
Java中时间戳转换为时间
Java中将时间戳转为日期时间字符串示例:
848 0