spring mvc示例

Welcome to Spring MVC Example. Sometime back in Spring MVC Tutorial, I explained how to create Spring MVC application using Spring Tool Suite. But today, I will be creating a basic hello world spring MVC application using maven and Eclipse.

欢迎使用Spring MVC示例。 有时在Spring MVC教程中 ,我解释了如何使用Spring Tool Suite创建Spring MVC应用程序。 但是今天,我将使用maven和Eclipse创建一个基本的hello world spring MVC应用程序。

Spring MVC示例 (Spring MVC Example)

Spring MVC is based on Model-View-Controller architecture. Below image shows Spring MVC architecture at a high level.

Spring MVC基于模型-视图-控制器体系结构。 下图从高层次显示了Spring MVC架构。

DispatcherServlet is the front controller class to take all requests and start processing them. We have to configure it in web.xml file. It’s job is to pass request to appropriate controller class and send the response back when view pages have rendered the response page.

DispatcherServlet是前端控制器类,用于接收所有请求并开始处理它们。 我们必须在web.xml文件中对其进行配置。 它的工作是将请求传递给适当的控制器类,并在视图页面呈现响应页面时将响应发送回去。

HomeController.java will be the single controller class in our spring mvc example application.

HomeController.java将是我们的spring mvc示例应用程序中的单个控制器类。

home.jsp, user.jsp are the view pages in our spring mvc hello world example application.

home.jspuser.jsp是我们的spring mvc hello world示例应用程序中的视图页面。

User.java will be the only model class we will have in our spring mvc example web application.

User.java将是我们在Springmvc示例Web应用程序中拥有的唯一模型类。

Spring MVC示例Hello World Eclipse项目 (Spring MVC Example Hello World Eclipse Project)

Below image shows our Spring MVC example project in Eclipse.

下图显示了我们在Eclipse中的Spring MVC示例项目。

Let’s get started and create our project right from the scratch.

让我们开始并从头开始创建我们的项目。

Spring MVC示例Eclipse项目设置 (Spring MVC Example Eclipse Project Setup)

Since it’s a web application and we want to use maven for dependencies management, first of all we have to create a dynamic web application and then convert it to a maven project. Below images show how to do this and get our project skeleton structure ready.

由于它是一个Web应用程序,并且我们想使用Maven进行依赖项管理,因此首先我们必须创建一个动态Web应用程序,然后将其转换为Maven项目。 下图显示了如何执行此操作并准备好我们的项目骨架结构。

Right click on the project explorer window and click on “New -> Dynamic Web Project” as shown in below image.

右键单击项目浏览器窗口,然后单击“新建->动态Web项目”,如下图所示。

Provide name as “spring-mvc-example” in the next popup page, rest of the things should not required to be changed.

在下一个弹出页面中将名称提供为“ spring-mvc-example”,其余的事情不需要更改。

On next page, provide the source folder as “src/main/java”. You might have to remove “src” folder from the list before adding this.

在下一页上,将源文件夹提供为“ src / main / java”。 在添加此文件夹之前,您可能必须从列表中删除“ src”文件夹。

Next is the web module page, provide the context root of application as “spring-mvc-example” and make sure to check “Generate web.xml deployment descriptor” option.

接下来是Web模块页面,提供应用程序的上下文根作为“ spring-mvc-example”,并确保选中“ Generate web.xml部署描述符”选项。

Click on Finish and you will have a new Dynamic Web Project in your eclipse project explorer.

单击Finish,您的Eclipse项目资源管理器中将有一个新的Dynamic Web Project。

将动态Web项目转换为Maven项目 (Converting Dynamic Web Project to Maven Project)

We want to use maven for easily manage our spring mvc dependencies. So let’s convert our web project to maven.

我们想使用Maven轻松管理我们的Spring MVC依赖关系。 因此,让我们将Web项目转换为Maven。

Right click on the project and select “Configure -> Convert to Maven Project”.

右键单击项目,然后选择“配置->转换为Maven项目”。

Next provide the pom.xml configurations as shown below.

接下来,提供pom.xml配置,如下所示。

Our maven web application project skeleton code is ready. Now we can start making changes to it and create our spring mvc hello world example application.

我们的Maven Web应用程序项目框架代码已准备就绪。 现在我们可以开始对其进行更改,并创建我们的spring mvc hello world示例应用程序。

Spring MVC对pom.xml的依赖 (Spring MVC Dependencies to pom.xml)

We need to add spring-web and spring-webmvc dependencies in pom.xml, also add servlet-api, jsp-api and jstl dependencies. Our final pom.xml file will be like below.

我们需要在pom.xml中添加spring-web和spring-webmvc依赖关系,还需要添加servlet-api,jsp-api和jstl依赖关系。 我们最终的pom.xml文件将如下所示。

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.journaldev.spring.mvc</groupId><artifactId>spring-mvc-example</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>Spring MVC Example</name><description>Spring MVC Hello World Example</description><!-- Add Spring Web and MVC dependencies --><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.9.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>4.3.9.RELEASE</version></dependency><!-- Servlet --><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.1</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency></dependencies><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.6.1</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.0.0</version><configuration><warSourceDirectory>WebContent</warSourceDirectory></configuration></plugin></plugins><finalName>${project.artifactId}</finalName> <!-- added to remove Version from WAR file --></build>
</project>

Notice the finalName configuration in build, so that our WAR file name doesn’t have version details.

请注意构建中的finalName配置,因此我们的WAR文件名没有版本详细信息。

When the project is build by Eclipse, you will notice all the jars showing up in maven dependencies section.

当该项目由Eclipse构建时,您会注意到在maven依赖项部分中显示了所有jar。

Spring MVC DispatcherServlet作为前端控制器 (Spring MVC DispatcherServlet as Front Controller)

We have to add Spring MVC framework to our web application, for that we need to configure DispatcherServlet in web.xml as shown below.

我们必须将Spring MVC框架添加到我们的Web应用程序中,为此,我们需要在web.xml中配置DispatcherServlet ,如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"><display-name>spring-mvc-example</display-name><!-- Add Spring MVC DispatcherServlet as front controller --><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring</servlet-name><url-pattern>/</url-pattern> </servlet-mapping></web-app>

contextConfigLocation init-param is used to provide the location of spring bean configuration file.

contextConfigLocation init-param用于提供Spring bean配置文件的位置。

Spring MVC示例Bean配置文件 (Spring MVC Example Bean Configuration File)

Next step is to create spring bean configuration file spring-servlet.xml as shown below.

下一步是创建spring bean配置文件spring-servlet.xml ,如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"xmlns:context="https://www.springframework.org/schema/context"xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsdhttps://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsdhttps://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --><!-- Enables the Spring MVC @Controller programming model --><annotation-driven /><context:component-scan base-package="com.journaldev.spring" /><!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --><beans:beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean></beans:beans>

There are three important configurations.

有三个重要的配置。

  1. annotation-driven tells DispatcherServlet to look for Controller classes using @Controller annotation.annotation-driven告诉DispatcherServlet使用@Controller 注解查找Controller类。
  2. context:component-scan tells DispatcherServlet where to look for controller classes.context:component-scan告诉DispatcherServlet在哪里寻找控制器类。
  3. InternalResourceViewResolver bean configuration to specify location of view pages and suffix used. Controller class methods return name of the view page and then suffix is added to figure out the view page to use for rendering the response.InternalResourceViewResolver bean配置,以指定视图页面的位置和所使用的后缀。 控制器类方法返回视图页面的名称,然后添加后缀以找出视图页面以用于呈现响应。

Spring MVC控制器类 (Spring MVC Controller Class)

We have a single controller class to respond for two URIs – “/” for home page and “/user” for user page.

我们有一个控制器类来响应两个URI –“ /”代表主页,“ / user”代表用户页面。

package com.journaldev.spring.controller;import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;import com.journaldev.spring.model.User;@Controller
public class HomeController {/*** Simply selects the home view to render by returning its name.*/@RequestMapping(value = "/", method = RequestMethod.GET)public String home(Locale locale, Model model) {System.out.println("Home Page Requested, locale = " + locale);Date date = new Date();DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);String formattedDate = dateFormat.format(date);model.addAttribute("serverTime", formattedDate);return "home";}@RequestMapping(value = "/user", method = RequestMethod.POST)public String user(@Validated User user, Model model) {System.out.println("User Page Requested");model.addAttribute("userName", user.getUserName());return "user";}
}

Note that for simplicity, I have not used any logging framework such as log4j.

请注意,为简单起见,我没有使用任何日志框架,例如log4j 。

Spring MVC模型类 (Spring MVC Model Class)

We have a simple model class with a single variable and it’s getter-setter methods. It’s a simple POJO class.

我们有一个带有单个变量的简单模型类,它是getter-setter方法。 这是一个简单的POJO类。

package com.journaldev.spring.model;public class User {private String userName;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}
}

Spring MVC查看页面 (Spring MVC View Pages)

We have two view pages as defined below.

我们有两个如下定义的视图页面。

home.jsp

home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Home</title>
</head>
<body><h1>Hello world!</h1><P>The time on the server is ${serverTime}.</p><form action="user" method="post"><input type="text" name="userName"><br> <inputtype="submit" value="Login"></form>
</body>
</html>

user.jsp

user.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Home Page</title>
</head>
<body>
<h3>Hi ${userName}</h3>
</body>
</html>

Notice that Spring MVC takes care of mapping form variables to model class variables, that’s why we have same variable name in both places.

注意,Spring MVC负责将表单变量映射到模型类变量,这就是为什么我们在两个地方都使用相同的变量名的原因。

That’s it, our spring mvc example project is ready to de deployed and test.

就是这样,我们的spring mvc示例项目已准备好进行部署和测试。

Spring MVC Eclipse项目部署 (Spring MVC Eclipse Project Deployment)

We can use Eclipse export as WAR file option to deploy it directly to any running tomcat server webapps directory. However you can also use command line to build the project and then copy it into your favourite servlet container deployment directory.

我们可以使用Eclipse导出为WAR文件选项将其直接部署到任何正在运行的tomcat服务器webapps目录中。 但是,您也可以使用命令行来构建项目,然后将其复制到您喜欢的servlet容器部署目录中。

Spring MVC示例测试 (Spring MVC Example Test)

Once the spring mvc project is deployed, we can access the home page at https://localhost:8080/spring-mvc-example/. Change the tomcat port and context-root accordingly.

部署spring mvc项目后,我们可以访问https://localhost:8080/spring-mvc-example/的主页。 相应地更改tomcat端口和上下文根。

That’s all for Spring MVC example, I have tried to keep it as simple as possible. But still if you face any issues then please let me know through comments and I will try to help you out. You can download the final spring mvc example project from below link.

这就是Spring MVC示例的全部内容,我尝试使其保持尽可能简单。 但是,如果您仍然遇到任何问题,请通过评论让我知道,我会尽力帮助您。 您可以从下面的链接下载最终的spring mvc示例项目。

Download Spring MVC Example Project下载Spring MVC示例项目

References: Official Page

参考: 官方页面

翻译自: https://www.journaldev.com/14476/spring-mvc-example

spring mvc示例

spring mvc示例_Spring MVC示例相关推荐

  1. spring mvc教程_Spring MVC教程

    spring mvc教程 1.简介 作为企业Java开发人员,这项工作的主要重点之一是开发Web应用程序. 对于Web应用程序,后果还包括许多挑战. 具体来说,其中一些是状态管理,工作流和验证. HT ...

  2. spring aop示例_Spring批处理示例

    spring aop示例 Welcome to Spring Batch Example. Spring Batch is a spring framework module for executio ...

  3. spring mvc国际化_Spring MVC国际化(i18n)和本地化(L10n)示例

    spring mvc国际化 Welcome to the Spring Internationalization (i18n) tutorial. Any web application with u ...

  4. spring mvc原理_Spring MVC的工作原理,我们来看看其源码实现

    来源:https://www.cnblogs.com/youzhibing/p/10695012.html 作者:youzhibing2904 遗留问题 在关于利用maven搭建ssm的博客,我们一起 ...

  5. java spring 拦截器_Spring MVC拦截器(Interceptor)的配置及使用

    在开发一个网站时可能有这样的需求:某些页面只希望几个特定的用户浏览.对于这样的访问权限控制,应该如何实现呢?拦截器就可以实现上述需求.在 Struts 2 框架中,拦截器是其重要的组成部分,Sprin ...

  6. spring框架mvc框架_Spring MVC测试框架入门–第2部分

    spring框架mvc框架 这个迷你系列的第一个博客介绍了Spring MVC测试框架,并演示了其在单元测试Spring MVC Controller类中作为控制器而不是POJO进行单元测试的用途. ...

  7. spring mvc 教程_Spring MVC开发–快速教程

    spring mvc 教程 这是我们的JCG合作伙伴之一,来自Manoj的有关使用Spring开发Web应用程序的简短教程, 网址为" The Khangaonkar Report &quo ...

  8. spring aop示例_Spring JpaRepository示例(内存中)

    spring aop示例 这篇文章描述了一个使用内存中HSQL数据库的简单Spring JpaRepository示例. 该代码示例可从GitHub的Spring-JpaRepository目录中获得 ...

  9. java spring mvc 实例_spring mvc 简单实例

    转至:http://blog.csdn.net/dingx/article/details/2242105 Spring Framework可以被使用在很多场合之中,考虑到目前大多数Java EE的项 ...

最新文章

  1. UA MATH564 概率论 多项分布
  2. iOS 自带 MD5转化
  3. 离线版的SAP中F1帮助
  4. BZOJ 3218 UOJ #77 A+B Problem (主席树、最小割)
  5. MATLAB中改变默认当前文件夹
  6. redis提高查询速度_面试小点-MySQL 的两种索引方法如何提高查询速度
  7. 点到面距离公式向量法_点到线或面的距离公式
  8. 编写Arduino支持的C++类库
  9. A/D采样控制电路设计---VHDL
  10. VCC、VDD、VEE、VSS的区别
  11. el-tooltip位置不灵活_要提高步伐移动的灵活性,注意这5点,加以改正,步伐不再沉重...
  12. cocos2d-x的CCSequence与CCRepeatForever的混用
  13. 书单丨刷完这5本题库,妈妈再也不用担心我的面试
  14. 解决连接本地oracle无监听的问题
  15. Zend Studio IDE使用yii framework框架无代码提示的解决方法
  16. Python解析JSON对象
  17. 计算机Excel应用案例,Excel VBA在Office中的应用案例
  18. 智慧城市:Web GIS 地图应用 IOC 运营中心
  19. Redis下载与安装
  20. WORD文档未保存就关闭的解决方法

热门文章

  1. Linux运维需要掌握的技能 (转)
  2. Visual Studio 2013/2015/2017快捷键(转)
  3. 8.26~8.30-广州软件所-实习工作日记
  4. 把应用程序从 Internet Explorer 迁移到 Mozilla
  5. P3615 如厕计划
  6. 44 The shopping psychology 购物心理
  7. 【蓝桥杯单片机11】单总线温度传感器DS18B20的基本操作
  8. iOS 基础 第五天(0811)
  9. Install Java on Ubuntu server
  10. 让不同的库元件继承自共同的类