最简单的 Spring MVC 框架教程 - 带有 UI (JSP) 页面的 Hello World 示例
已发表: 2019-02-23
模型-视图-控制器 (MVC) 架构提供了开发灵活且松散耦合的 Web 应用程序的最简单方法。
在本教程中,我们将介绍如何通过非常详细的步骤创建您的第一个 Spring MVC 应用程序。
您有以下任何问题吗?
- Spring MVC 5.2.3 基础
- 逐步开发 Spring Framework MVC 5 应用程序。
- java - 从零开始的 Spring MVC 教程
- Spring MVC 快速教程
- Spring MVC 框架教程
- 第一篇 Spring MVC 应用教程
- Spring 5.x MVC 教程、AJAX 演示、jQuery 演示、JavaScript 演示、提示和技巧 Spring 5 MVC
那么你来对地方了。 在这里,我将演示用于构建 Web 应用程序的简单Spring MVC framework
。
第一件事——让我们设置环境
教程最后更新和验证时间:2020 年 9 月,工具版本如下。
我正在使用以下工具,如果您还没有,您可能需要下载这些工具。
- Tomcat 9.0.38 – 从此链接下载最新的 Apache Tomcat。
- 确保下载 Eclipse IDE for
Java EE
Developers (2020‑09 R) – 下载链接。 (下图) -
Spring 5.2.9.RELEASE
(无需下载)——我们将使用 Maven 依赖项。 - JDK 15 – 下载链接。

确保下载最新Java EE
Developer Kit:

主要目标
本教程的主要目标是以最简单的方式创建 Spring MVC 应用程序。
在我们开始之前,让我们看看我们将在本教程结束时看到什么
这就是我们的application result
的样子。 这是完成以下所有步骤后的最终结果。
这是最终结果:欢迎页面 ==> index.jsp

从控制器类返回结果

现在让我们开始教程
第1步
- 打开日食
- 创建
New Eclipse Workspace
——这must
避免任何现有的工作区配置问题。

第2步
- 点击
File
- 点击
New
- 选择
Dynamic Web Project
- 一个弹出窗口,提供项目名称:
CrunchifySpringMVCTutorial
- 确保将
Target Runtime
用作Apache Tomcat 9.0
- 如果您没有看到 Target Runtime,请按照以下步骤操作
- 选择配置作为
Default Configuration

第三步
将项目转换为 Maven 项目以将所有必需的 Spring MVC 依赖项添加到项目中。
脚步:
- 右键单击项目
- 配置
- 转换为
Maven
项目


第四步
打开pom.xml
文件并将下面的jar dependencies
项添加到项目中。

NOTE:
这是我的pom.xml
文件。 如果您尚未迁移到JDK 13
13
我们将不断更新本教程到最新的 Spring MVC 版本。所以下面的 pom.xml 文件可能具有与上图不同的(最新)版本的 Spring MVC 依赖项
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi : schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > CrunchifySpringMVCTutorial < / groupId > < artifactId > CrunchifySpringMVCTutorial < / artifactId > < version > 0.0.1 - SNAPSHOT < / version > < packaging > war < / packaging > < build > < sourceDirectory > src < / sourceDirectory > < plugins > < plugin > < artifactId > maven - compiler - plugin < / artifactId > < version > 3.8.0 < / version > < configuration > < release > 13 < / release > < / configuration > < / plugin > < plugin > < artifactId > maven - war - plugin < / artifactId > < version > 3.2.1 < / version > < configuration > < warSourceDirectory > WebContent < / warSourceDirectory > < / configuration > < / plugin > < / plugins > < / build > < dependencies > < dependency > < groupId > org . springframework < / groupId > < artifactId > spring - core < / artifactId > < version > 5.2.3.RELEASE < / version > < / dependency > < dependency > < groupId > org . springframework < / groupId > < artifactId > spring - context < / artifactId > < version > 5.2.3.RELEASE < / version > < / dependency > < dependency > < groupId > org . springframework < / groupId > < artifactId > spring - aop < / artifactId > < version > 5.2.3.RELEASE < / version > < / dependency > < dependency > < groupId > org . springframework < / groupId > < artifactId > spring - webmvc < / artifactId > < version > 5.2.3.RELEASE < / version > < / dependency > < dependency > < groupId > org . springframework < / groupId > < artifactId > spring - web < / artifactId > < version > 5.2.3.RELEASE < / version > < / dependency > < dependency > < groupId > javax . servlet < / groupId > < artifactId > jstl < / artifactId > < version > 1.2 < / version > < / dependency > < / dependencies > < / project > |
第 5 步
创建新的 Spring 配置Bean
文件: /WebContent/WEB-INF/crunchify-servlet.xml

crunchify-servlet.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<? xml version = "1.0" encoding = "UTF-8" ?> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns : mvc = "http://www.springframework.org/schema/mvc" xmlns : context = "http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > < mvc : annotation - driven / > < context : component - scan base - package = "com.crunchify.controller" / > < mvc : default - servlet - handler / > < bean id = "viewResolver" class = "org.springframework.web.servlet.view.UrlBasedViewResolver" > < property name = "viewClass" value = "org.springframework.web.servlet.view.JstlView" / > < property name = "prefix" value = "/WEB-INF/jsp/" / > < property name = "suffix" value = ".jsp" / > < / bean > < / beans > |
在上面的crunchify-servlet.xml
在配置文件中,我们定义了一个标签<context:component-scan>
。 这将允许 Spring 从包com.crunchify.controller
及其所有子包中加载所有组件。
这将加载我们的CrunchifyHelloWorld.class
。 我们还定义了一个 bean viewResolver
。 此 bean 将解析视图并将前缀字符串/WEB-INF/jsp/
和后缀.jsp
添加到 ModelAndView 中的视图。
请注意,在我们的CrunchifyHelloWorld
类中,我们返回了一个带有视图名称 Welcome 的 ModelAndView 对象。
这将被解析为路径/WEB-INF/jsp/welcome.jsp
。
第 6 步
如果新文件web.xml
不存在,则创建它。 在/WebContent/WEB-INF/web.xml
文件中映射 Spring MVC。
NOTE:
如果您在“ dynamic web project
”中没有看到 web.xml 文件,请按照以下步骤操作。
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<? xml version = "1.0" encoding = "UTF-8" ?> < web - app xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xsi : schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id = "WebApp_ID" version = "4.0" > < display - name > CrunchifySpringMVCTutorial < / display - name > < welcome - file - list > < welcome - file > index . html < / welcome - file > < welcome - file > index . htm < / welcome - file > < welcome - file > index . jsp < / welcome - file > < welcome - file > default . html < / welcome - file > < welcome - file > default . htm < / welcome - file > < welcome - file > default . jsp < / welcome - file > < / welcome - file - list > < servlet > < servlet - name > crunchify < / servlet - name > < servlet - class > org . springframework . web . servlet . DispatcherServlet < / servlet - class > < load - on - startup > 1 < / load - on - startup > < / servlet > < servlet - mapping > < servlet - name > crunchify < / servlet - name > < url - pattern > / welcome . jsp < / url - pattern > < url - pattern > / index . jsp < / url - pattern > < url - pattern > / welcome . html < / url - pattern > < url - pattern > * . html < / url - pattern > < / servlet - mapping > < / web - app > |
web.xml
中的上述代码将使用 url 模式/welcome.jsp
映射 DispatcherServlet。 另请注意,我们已将index.jsp
定义为欢迎文件。
这里要注意的一件事是web.xml
中<servlet-name>
标记中的 servlet 名称。 一旦 DispatcherServlet 被初始化,它将在 Web 应用程序的 WEB-INF 文件夹中查找文件名[servlet-name]-servlet.xml
。 在此示例中,框架将查找名为crunchify-servlet.xml
。
第 7 步
创建控制器类。
- 右键单击
Java Resources
->src
- 单击
New
->Class
- 包:
com.crunchify.controller
- 文件名:
CrunchifyHelloWorld.java

CrunchifyHelloWorld.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com . crunchify . controller ; import org . springframework . stereotype . Controller ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . servlet . ModelAndView ; /* * author: Crunchify.com * */ @Controller public class CrunchifyHelloWorld { @RequestMapping ( "/welcome" ) public ModelAndView helloWorld ( ) { String message = "<br><div>" + "<h3>********** Hello World, Spring MVC Tutorial</h3>This message is coming from CrunchifyHelloWorld.java **********</div><br><br>" ; return new ModelAndView ( "welcome" , "message" , message ) ; } } |
请注意,我们已经使用@Controller
和@RequestMapping("/welcome")
注释了CrunchifyHelloWorld
类。 当 Spring 扫描我们的包时,它会将这个 bean 识别为用于处理请求的 Controller bean。 @RequestMapping
注解告诉 Spring 这个 Controller 应该处理 URL 路径中以 /welcome 开头的所有请求。 这包括/welcome/*
和/welcome.html
。

helloWorld() 方法返回ModelAndView
对象。 ModelAndView 对象试图解析一个名为“welcome”的视图,并且数据模型被传回浏览器,以便我们可以访问 JSP 中的数据。 逻辑视图名称将解析为/WEB-INF/jsp/welcome.jsp
。 在 ModelAndView 对象中返回的逻辑名称“welcome”映射到路径 /WEB-INF/jsp/welcome.jsp。
ModelAndView 对象还包含一条带有键“消息”和详细值的消息。 这是我们传递给视图的数据。 通常这将是一个 java bean 形式的值对象,它将包含要在我们的视图上显示的数据。 这里我们只是传递一个字符串。
步骤 8
视图 –创建新文件/WebContent/index.jsp
。
索引.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
< html > < head > < title > Spring MVC Tutorial Series by Crunchify . com < / title > <style type ="text/css"> body { background-image : url ( 'https://cdn.crunchify.com/bg.png' ) ; } </style> < / head > < body > < br > < div style = "text-align: center" > < h2 > Hey You . . ! ! This is your 1st Spring MCV Tutorial . . < br > < br > < / h2 > < h3 > < a href = "welcome.html" > Click here to See Welcome Message . . . < / a > ( to check Spring MVC Controller . . . @ RequestMapping ( "/welcome" ) ) < / h3 > < / div > < / body > < / html > |
创建另一个文件/WebContent/WEB-INF/jsp/welcome.jsp
。
NOTE:
不要忘记创建jsp
文件夹并将welcome.jsp
放入其中
欢迎.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
< html > < head > < title > Spring MVC Tutorial by Crunchify - Hello World Spring MVC Example < / title > <style type ="text/css"> body { background-image : url ( 'https://cdn.crunchify.com/bg.png' ) ; } </style> < / head > < body > $ { message } < br > < br > < div style = "font-family: verdana; padding: 10px; border-radius: 10px; font-size: 12px; text-align: center;" > Spring MCV Tutorial by < a href = "https://crunchify.com" > Crunchify < / a > . Click < a href = "https://crunchify.com/category/java-tutorials/" target = "_blank" > here < / a > for all Java and < a href = 'https://crunchify.com/category/spring-mvc/' target = '_blank' > here < / a > for all Spring MVC , Web Development examples . < br > < / div > < / body > < / html > |
毕竟,这就是您的工作区应该是什么样子。

第 9 步
右键单击Project -> Run As -> Maven Build...

Add Goals
: clean install
。 单击Apply
并Run
。

您应该看到构建success message
:

我所有的 .jar 文件在哪里?
您将在/target
文件夹下看到所有 .jar 文件。 截屏。
第十步
- 如果您在
Servers
选项卡中don't see
Tomcat 服务器,请按照步骤将 Apache Tomcat 添加到 Eclipse。 - 将项目部署到
Apache Tomcat
- 右键点击
- 添加和删除
- 将项目添加到服务器(右侧部分)。
- 单击开始。

确保您看到以下日志。 这意味着您的应用程序已成功部署在 Tomcat Web 服务器上。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
Aug 04 , 2018 9 : 08 : 10 PM org . apache . tomcat . util . digester . SetPropertiesRule begin WARNING : [ SetPropertiesRule ] { Server / Service / Engine / Host / Context } Setting property 'source' to 'org.eclipse.jst.jee.server:CrunchifySpringMVCTutorial' did not find a matching property . INFO : Server version : Apache Tomcat / 9.0.10 INFO : Server built : Jun 20 2018 17 : 32 : 21 UTC INFO : Server number : 9.0.10.0 INFO : OS Name : Mac OS X INFO : OS Version : 10.13.6 INFO : Architecture : x86_64 INFO : Java Home : / Library / Java / JavaVirtualMachines / jdk - 10.0.2.jdk / Contents / Home INFO : JVM Version : 10.0.2 + 13 INFO : JVM Vendor : "Oracle Corporation" INFO : CATALINA_BASE : / Users / appshah / Documents / jee - photon / workspace / c / . metadata / . plugins / org . eclipse . wst . server . core / tmp0 INFO : CATALINA_HOME : / Users / appshah / Documents / jee - photon / apache - tomcat - 9.0.10 INFO : Command line argument : - Dcatalina . base =/ Users / appshah / Documents / jee - photon / workspace / c / . metadata / . plugins / org . eclipse . wst . server . core / tmp0 INFO : Command line argument : - Dcatalina . home =/ Users / appshah / Documents / jee - photon / apache - tomcat - 9.0.10 INFO : Command line argument : - Dwtp . deploy =/ Users / appshah / Documents / jee - photon / workspace / c / . metadata / . plugins / org . eclipse . wst . server . core / tmp0 / wtpwebapps INFO : Command line argument : - Dfile . encoding = UTF - 8 INFO : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java . library . path : [ / Users / appshah / Library / Java / Extensions : / Library / Java / Extensions : / Network / Library / Java / Extensions : / System / Library / Java / Extensions : / usr / lib / java : . ] INFO : Initializing ProtocolHandler [ "http-nio-8080" ] INFO : Using a shared selector for servlet write / read INFO : Initializing ProtocolHandler [ "ajp-nio-8009" ] INFO : Using a shared selector for servlet write / read INFO : Initialization processed in 841 ms INFO : Starting service [ Catalina ] INFO : Starting Servlet Engine : Apache Tomcat / 9.0.10 INFO : At least one JAR was scanned for TLDs yet contained no TLDs . Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them . Skipping unneeded JARs during scanning can improve startup time and JSP compilation time . INFO : At least one JAR was scanned for TLDs yet contained no TLDs . Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them . Skipping unneeded JARs during scanning can improve startup time and JSP compilation time . INFO : No Spring WebApplicationInitializer types detected on classpath INFO : Initializing Spring FrameworkServlet 'crunchify' INFO : FrameworkServlet 'crunchify' : initialization started INFO : Refreshing WebApplicationContext for namespace 'crunchify-servlet' : startup date [ Sat Aug 04 21 : 08 : 13 CDT 2018 ] ; root of context hierarchy INFO : Loading XML bean definitions from ServletContext resource [ / WEB - INF / crunchify - servlet . xml ] INFO : Mapped "{[/welcome]}" onto public org . springframework . web . servlet . ModelAndView com . crunchify . controller . CrunchifyHelloWorld . helloWorld ( ) INFO : Looking for @ ControllerAdvice : WebApplicationContext for namespace 'crunchify-servlet' : startup date [ Sat Aug 04 21 : 08 : 13 CDT 2018 ] ; root of context hierarchy INFO : Looking for @ ControllerAdvice : WebApplicationContext for namespace 'crunchify-servlet' : startup date [ Sat Aug 04 21 : 08 : 13 CDT 2018 ] ; root of context hierarchy INFO : Mapped URL path [ /** ] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0' INFO : FrameworkServlet 'crunchify' : initialization completed in 1607 ms INFO : Starting ProtocolHandler [ "http-nio-8080" ] INFO : Starting ProtocolHandler [ "ajp-nio-8009" ] INFO : Server startup in 3579 ms |
步骤 11。 完毕。
访问:http://localhost:8080/CrunchifySpringMVCTutorial/ 你应该已经准备好了。
万岁.. 现在您知道Hello World Spring MVC 5 Example
。 如果您在运行此程序时遇到任何异常,请告诉我。 您可以在此处找到更多示例。
Do you want to include JS, CSS and images into JSP file?
遵循本教程:使用“mvc:resources mapping”将 JS、CSS 和图像添加/集成到 JSP 文件中的最佳方法。
遇到麻烦? 有什么问题吗?
分类第 1 步 – 出现 HTTP 状态 404 错误?
另外,请按照以下教程进行操作:
分类第 2 步 – URL 不起作用? Tomcat错误?
确保将 Apache Tomcat Server 添加到Targeted Runtime
。 您可能在Step-1
中选择了它。 Tomcat 7 或 8 any – 服务器应该可以工作。

分类第 3 步 – maven 错误?
确保更新所有 Maven 依赖项。

如果您在运行以上教程时遇到任何问题,请随时通过电子邮件发送或在下方发表评论。