2015 最简单的 Spring MVC 入门教程

2015 最简单的 Spring MVC 入门教程

太阳火神的美丽人生 (http://blog.csdn.net/opengl_es)

本文遵循“署名-非商业用途-保持一致”创作公用协议

转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS、Android、Html5、Arduino、pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作。

Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

SHORT LINK: 

Last Updated on October 22nd, 2015 by Crunchify 179 Comments

Do you have any one of below question?

  • Developing a Spring Framework MVC 4 application step-by-step..
  • java – Spring MVC tutorial from the scratch
  • Spring MVC Fast Tutorial
  • Spring MVC Framework Tutorial
  • First Spring MVC application tutorial
  • Spring 4 MVC Tutorials, AJAX DemojQuery DemoJavaScript Demo, Tips & Tricks Spring 4 MVC

Then you are at right place. Here I’ll demonstrate simple Spring MVC framework for building web applications.

First thing first. I’m using below tools which you may need to download if you don’t have already.

  1. Tomcat 7.0.65 – Download link.
  2. Eclipse IDE for Java EE Developers (Mars v4.5.1) – Download link.
  3. Spring 4.2.2 (No download required) – we will use Maven dependency.
  4. JDK 1.8 – Download link.

Main goal for this tutorial to create Spring MVC Application in the simplest way. This is how ourapplication result will look like. This is a final result once you complete all below steps.

Welcome page ==> index.jsp

Result returns from Controller Class 

Now Let’s get started

Step-1

Open Eclipse and Create Dynamic Web Project CrunchifySpringMVCTutorial.

Step-2

Make sure you use Target Runtime as Apache Tomcat 7.0

Step-3

Convert Project to Maven Project to add all required Spring MVC dependencies to project.

Steps:

  • Right click on project
  • Configure
  • Convert to Maven project

Step-4

Open pom.xml file and add below jar dependencies to project.

Here is my pom.xml file.

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

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

62

63

64

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

 

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.1.1.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aop</artifactId>

<version>4.1.1.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>4.1.1.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>4.1.1.RELEASE</version>

</dependency>

 

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

 

<dependency>

<groupId>commons-logging</groupId>

<artifactId>commons-logging</artifactId>

<version>1.1.3</version>

</dependency>

</dependencies>

<build>

<sourceDirectory>src</sourceDirectory>

<plugins>

<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.1</version>

<configuration>

<source>1.7</source>

<target>1.7</target>

</configuration>

</plugin>

<plugin>

<artifactId>maven-war-plugin</artifactId>

<version>2.4</version>

<configuration>

<warSourceDirectory>WebContent</warSourceDirectory>

<failOnMissingWebXml>false</failOnMissingWebXml>

</configuration>

</plugin>

</plugins>

</build>

</project>

Step-5

Create Spring Configuration Bean file. /WebContent/WEB-INF/crunchify-servlet.xml

/WEB-INF/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

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

 

<context:component-scan base-package="com.crunchify.controller" />

 

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

In the above crunchify-servlet.xml  configuration file, we have defined a tag <context:component-scan> . This will allow Spring to load all the components from package com.crunchify.controller  and all its child packages.

This will load our CrunchifyHelloWorld.class . Also we have defined a bean viewResolver. This bean will resolve the view and add prefix string /WEB-INF/jsp/  and suffix .jsp to the view in ModelAndView. Note that in our CrunchifyHelloWorld class, we have return a ModelAndView object with view name welcome. This will be resolved to path /WEB-INF/jsp/welcome.jsp .

Step-6

Map Spring MVC in /WebContent/WEB-INF/web.xml file.

NOTE: if you don’t see web.xml file in your “dynamic web project” then follow these steps.

/WEB-INF/web.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

  <display-name>CrunchifySpringMVCTutorial</display-name>

  <welcome-file-list>

    <welcome-file>index.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>/welcome.html</url-pattern>

        <url-pattern>*.html</url-pattern>

    </servlet-mapping>

  

</web-app>

The above code in web.xml will map DispatcherServlet with url pattern /welcome.jsp. Also note that we have define index.jsp as welcome file.

One thing to note here is the name of servlet in <servlet-name> tag in web.xml. Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml  in WEB-INF folder of web application. In this example, the framework will look for file called crunchify-servlet.xml.

Step-7

Create Controller Class.

  • Package: com.crunchify.controller
  • Filename: CrunchifyHelloWorld.java

com.crunchify.controller.CrunchifyHelloWorld.java
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 style='text-align:center;'>"

+ "<h3>********** Hello World, Spring MVC Tutorial</h3>This message is coming from CrunchifyHelloWorld.java **********</div><br><br>";

return new ModelAndView("welcome", "message", message);

}

}

Note that we have annotated the CrunchifyHelloWorld class with @Controller and@RequestMapping("/welcome"). When Spring scans our package, it will recognize this bean as being a Controller bean for processing requests. The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /welcome in the URL path. That includes/welcome/* and /welcome.html.

The helloWorld() method returns ModelAndView object. The ModelAndView object tries to resolve to a view named “welcome” and the data model is being passed back to the browser so we can access the data within the JSP. The logical view name will resolve to /WEB-INF/jsp/welcome.jsp . Logical name “welcome” which is return in ModelAndView object is mapped to path /WEB-INF/jsp/welcome.jsp.

The ModelAndView object also contains a message with key “message” and Detailed value. This is the data that we are passing to our view. Normally this will be a value object in form of java bean that will contain the data to be displayed on our view. Here we are simply passing a string.

Step-8

The View – Create /WebContent/index.jsp.

index.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('http://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>

Create /WebContent/WEB-INF/jsp/welcome.jsp  file.

welcome.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('http://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="http://crunchify.com">Crunchify</a>.

Click <a

href="http://crunchify.com/category/java-web-development-tutorial/"

target="_blank">here</a> for all Java and <a

href='http://crunchify.com/category/spring-mvc/' target='_blank'>here</a>

for all Spring MVC, Web Development examples.<br>

</div>

</body>

</html>

After everything this is how your workspace should look like.

Step-9

Right Click on Project -> Run As -> Maven Build...

Add Goalsclean install. Click Apply and Run.

You should see build success message:

Where are all of my .jar files?

You will see all .jar files under /target folder. Screenshot.

Step-10

Deploy project to Apache Tomcat and start tomcat.

Make sure you see below logs. That means your application is successfully deployed on Tomcat Web Server.

Step-11

Visit: http://localhost:8080/CrunchifySpringMVCTutorial/ and you should be all set.

Hurrey.. Now you know Hello World Spring MVC 4 Example. Let me know if you encounter any exception while running this. There are lot more example you can find here.

Do you want to include JS, CSS and images into JSP file? Follow this tutorial: Best way to Add/Integrate JS, CSS and images into JSP file using ‘mvc:resources mapping’

Having trouble? Any issue?

Triaging step-1

Make sure you add Apache Tomcat Server to Targeted Runtime. Which you may have selected in Step-1. Tomcat 7 or 8 any – server should work.

Triaging Step-2

Make sure to update all maven dependencies.

Have anything to add to this article? Please chime in and join the conversion.

SHARE ON

TwitterFacebookGoogle+BufferFollow @Crunchify

Some more articles you might also be interested in …

  1. Spring MVC: How to Declare a Bean in Spring Application?
  2. Spring MVC Tutorial: How to Upload Multiple Files to Specific Location
  3. How to use AJAX, jQuery in Spring Web MVC (.jsp) – Example
  4. Spring MVC: Introduction to Spring 3 MVC Framework – Spring 4
  5. Spring MVC 4.2.2 – Best way to Add/Integrate JS, CSS and images into JSP file using ‘mvc:resources mapping’
  6. Working on Spring MVC Project? How to Report List of All Loaded Spring Beans during Startup?
  7. Servlet Tutorial: Getting Starting with JSP – Servlet Example
  8. How to import all Spring MVC Dependencies to your Maven Project?
  9. How to Update Sparkline Graph Every 3 Seconds in Spring MVC (Realtime Update)
  10. Spring MVC: How to Access ModelMap Values in a JSP?

Filed Under: Apache Tomcat ExamplesEclipseJava CollectionSpring MVC TutorialsTagged: crunchify tutorialDeveloping a Spring Framework MVC application step-by-stepeclipsejavajava spring mvcspringSpring 4Spring 4 MVC Hello World TutorialSpring 4 MVC Hello World Tutorial - Full ExampleSpring AOP 4spring frameworkSpring MVCspring mvc 3.2.1Spring MVC 4Spring MVC Ajaxspring mvc example,Spring MVC Fast TutorialSpring MVC Hello World Example

Enjoyed this post?

Be sure to subscribe to the Crunchify newsletter and get regular updates about awesome posts just like this one and more! Join more than 13000 subscribers!

Enter your email address... 


About Crunchify

Hello & Good Day from greater New York. Crunchify is founded by App Shah. He is a professional blogger & loves Web development hence Crunchify.com is his publication with more than 10 millions pageviews per month, that covers all aspects and tactics on Java, WordPress, J2EE (Enterprise Java), Spring MVC, Github, etc Technologies.

时间: 2024-10-27 16:26:10

2015 最简单的 Spring MVC 入门教程的相关文章

Spring MVC入门 —— 跟开涛学SpringMVC

2014-05-14 23:22:27 第二章 Spring MVC入门 -- 跟开涛学SpringMVC  浏览(84979)|评论(12)   交流分类:Java|笔记分类: 跟开涛学Spring--  2.1.Spring Web MVC是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring

史上最强Spring mvc入门

一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于SpringMVC的配置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <!--configure the setting of springmvcDispatcherServlet and configure the mapping--> <servlet>     <servlet-name>

一个简单的Spring MVC的例子

一.Spring MVC的优点 1.Spring3 MVC的学习难度小于Struts2,Struts2用不上的多余功能太多.呵呵,当然这不是决定因素. 2.Spring3 MVC很容易就可以写出性能优秀的程序,Struts2要处处小心才可以写出性能优秀的程序(指MVC部分) 3.Spring3 MVC的灵活是你无法想像的,Spring的扩展性有口皆碑,Spring3 MVC当然也不会落后,不会因使用了MVC框架而感到有任何的限制. 二.简单的例子 1.配置web.xml 指除了Control层外

Eclipse使用maven搭建spring mvc图文教程_java

本文为大家介绍了Eclipse使用maven搭建spring mvc的详细步骤,供大家参考,具体内容如下 1. 环境配置 a). Java 1.7 b). Eclipse luna c). Maven3.2.5 d). Spring 4.1.4 2. 创建maven工程 a). 打开eclipse,file->new->project->Maven->Maven Project b). 下一步 c). 选择创建的工程为webapp,下一步 d). 填写项目的group id和art

Spring MVC 入门基础(一)

一.Spring Web MVC是什么? Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的. Spring Web MVC也是服务到工作者模式的实现,但进行可优化.[前端控制器是DispatcherServlet:应用控制器其实拆为处理映射器(Handle

PS为照片制作简单的雪景效果入门教程

原图 效果 打开素材,建立"通道混合器"调整图层 将此调整图层设为"强光"模式 相关教程: Photoshop制作大雪纷飞的动态雪景图 分类: PS入门教程

Spring MVC入门1

1.Spring MVC 和Struts一样是一个MVC框架,和Strusts2有点相似,和Spring无缝连接,属于Spring的一个框架. 2.环境搭建 1)在eclipse中新建动态web项目,注意版本选择2.5 2)导入所需要的jar包 3)编辑web.xml文件 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XM

spring MVC 入门程序

由上一篇文章的分析spring MVC主要有以下几个组成部分:dispatcherServlet.HandlerMapping.HandlerAdapter.Handler.ViewResolver.View.其中 DispatcherServlet:前端控制器,由springmvc提供 HandlerMappting:处理器映射器,由springmvc提供 HandlerAdapter:处理器适配器,由springmvc提供 Handler:处理器,需要程序员开发 ViewResolver:视

Spring - MVC Framework 教程

Spring - MVC Framework Tutorial 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. Spring - MVC Framework Tutorial Advertise