天天看點

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

2015 最簡單的 Spring MVC 入門教程

<a target="_blank" href="http://blog.csdn.net/opengl_es">轉載請保留此句:太陽火神的美麗人生 -  本部落格專注于 靈活開發及移動和物聯裝置研究:iOS、Android、Html5、Arduino、pcDuino,否則,出自本部落格的文章拒絕轉載或再轉載,謝謝合作。</a>

SHORT LINK: 

Do you have any one of below question?

Spring MVC Fast Tutorial

Spring MVC Framework Tutorial

First Spring MVC application tutorial

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.

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

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips
2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips
2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Open Eclipse and Create Dynamic Web Project <code>CrunchifySpringMVCTutorial</code>.

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips
2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Make sure you use <code>Target Runtime</code> as <code>Apache Tomcat 7.0</code>

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

Right click on project

Configure

Convert to Maven project

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Open <code>pom.xml</code> file and add below <code>jar dependencies</code> to project.

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Here is my <code>pom.xml</code> 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

&lt;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"&gt;

&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

&lt;groupId&gt;CrunchifySpringMVCTutorial&lt;/groupId&gt;

&lt;artifactId&gt;CrunchifySpringMVCTutorial&lt;/artifactId&gt;

&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;

&lt;packaging&gt;war&lt;/packaging&gt;

&lt;dependencies&gt;

&lt;dependency&gt;

&lt;groupId&gt;org.springframework&lt;/groupId&gt;

&lt;artifactId&gt;spring-context&lt;/artifactId&gt;

&lt;version&gt;4.1.1.RELEASE&lt;/version&gt;

&lt;/dependency&gt;

&lt;artifactId&gt;spring-aop&lt;/artifactId&gt;

&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;

&lt;artifactId&gt;spring-web&lt;/artifactId&gt;

&lt;groupId&gt;javax.servlet&lt;/groupId&gt;

&lt;artifactId&gt;jstl&lt;/artifactId&gt;

&lt;version&gt;1.2&lt;/version&gt;

&lt;groupId&gt;commons-logging&lt;/groupId&gt;

&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;

&lt;version&gt;1.1.3&lt;/version&gt;

&lt;/dependencies&gt;

&lt;build&gt;

&lt;sourceDirectory&gt;src&lt;/sourceDirectory&gt;

&lt;plugins&gt;

&lt;plugin&gt;

&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;

&lt;version&gt;3.1&lt;/version&gt;

&lt;configuration&gt;

&lt;source&gt;1.7&lt;/source&gt;

&lt;target&gt;1.7&lt;/target&gt;

&lt;/configuration&gt;

&lt;/plugin&gt;

&lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;

&lt;version&gt;2.4&lt;/version&gt;

&lt;warSourceDirectory&gt;WebContent&lt;/warSourceDirectory&gt;

&lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;

&lt;/plugins&gt;

&lt;/build&gt;

&lt;/project&gt;

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

/WEB-INF/crunchify-servlet.xml

&lt;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"&gt;

&lt;context:component-scan base-package="com.crunchify.controller" /&gt;

&lt;bean id="viewResolver"

class="org.springframework.web.servlet.view.UrlBasedViewResolver"&gt;

&lt;property name="viewClass"

value="org.springframework.web.servlet.view.JstlView" /&gt;

&lt;property name="prefix" value="/WEB-INF/jsp/" /&gt;

&lt;property name="suffix" value=".jsp" /&gt;

&lt;/bean&gt;

&lt;/beans&gt;

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

This will load our <code>CrunchifyHelloWorld.class</code> . Also we have defined a bean <code>viewResolver</code>. This bean will resolve the view and add prefix string <code>/WEB-INF/jsp/</code>  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 <code>/WEB-INF/jsp/welcome.jsp</code> .

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

/WEB-INF/web.xml

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;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"&gt;

  &lt;display-name&gt;CrunchifySpringMVCTutorial&lt;/display-name&gt;

  &lt;welcome-file-list&gt;

    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;

  &lt;/welcome-file-list&gt;

    &lt;servlet&gt;

        &lt;servlet-name&gt;crunchify&lt;/servlet-name&gt;

        &lt;servlet-class&gt;

            org.springframework.web.servlet.DispatcherServlet

        &lt;/servlet-class&gt;

        &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;

    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;

        &lt;url-pattern&gt;/welcome.jsp&lt;/url-pattern&gt;

        &lt;url-pattern&gt;/welcome.html&lt;/url-pattern&gt;

        &lt;url-pattern&gt;*.html&lt;/url-pattern&gt;

    &lt;/servlet-mapping&gt;

&lt;/web-app&gt;

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

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

Create Controller Class.

Package: com.crunchify.controller

Filename: CrunchifyHelloWorld.java

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

com.crunchify.controller.CrunchifyHelloWorld.javaJava

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 = "&lt;br&gt;&lt;div style='text-align:center;'&gt;"

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

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

}

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

The helloWorld() method returns <code>ModelAndView</code> 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 <code>/WEB-INF/jsp/welcome.jsp</code> . 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.

The View – Create <code>/WebContent/index.jsp</code>.

index.jsp

&lt;html&gt;

&lt;head&gt;

&lt;title&gt;Spring MVC Tutorial Series by Crunchify.com&lt;/title&gt;

&lt;style type="text/css"&gt;

body {

background-image: url('http://crunchify.com/bg.png');

&lt;/style&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;br&gt;

&lt;div style="text-align:center"&gt;

&lt;h2&gt;

Hey You..!! This is your 1st Spring MCV Tutorial..&lt;br&gt; &lt;br&gt;

&lt;/h2&gt;

&lt;h3&gt;

&lt;a href="welcome.html"&gt;Click here to See Welcome Message... &lt;/a&gt;(to

check Spring MVC Controller... @RequestMapping("/welcome"))

&lt;/h3&gt;

&lt;/div&gt;

&lt;/body&gt;

&lt;/html&gt;

Create <code>/WebContent/WEB-INF/jsp/welcome.jsp</code>  file.

welcome.jsp

&lt;title&gt;Spring MVC Tutorial by Crunchify - Hello World Spring MVC

Example&lt;/title&gt;

&lt;body&gt;${message}

&lt;div style="font-family: verdana; padding: 10px; border-radius: 10px; font-size: 12px; text-align:center;"&gt;

Spring MCV Tutorial by &lt;a href="http://crunchify.com"&gt;Crunchify&lt;/a&gt;.

Click &lt;a

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

target="_blank"&gt;here&lt;/a&gt; for all Java and &lt;a

href='http://crunchify.com/category/spring-mvc/' target='_blank'&gt;here&lt;/a&gt;

for all Spring MVC, Web Development examples.&lt;br&gt;

After everything this is how your workspace should look like.

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Right Click on <code>Project -&gt; Run As -&gt; Maven Build...</code>

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

<code>Add Goals</code>: <code>clean install</code>. Click <code>Apply</code> and <code>Run</code>.

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

You should see build success message:

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Deploy project to <code>Apache Tomcat</code> and start tomcat.

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

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

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

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

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Make sure to update all maven dependencies.

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

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

<a target="_blank" href="http://crunchify.com/spring-mvc-how-to-declare-a-bean-in-spring-application/">Spring MVC: How to Declare a Bean in Spring Application?</a>

<a target="_blank" href="http://crunchify.com/spring-mvc-tutorial-how-to-upload-multiple-files-to-specific-location/">Spring MVC Tutorial: How to Upload Multiple Files to Specific Location</a>

<a target="_blank" href="http://crunchify.com/how-to-use-ajax-jquery-in-spring-web-mvc-jsp-example/">How to use AJAX, jQuery in Spring Web MVC (.jsp) – Example</a>

<a target="_blank" href="http://crunchify.com/spring-mvc-introduction-to-spring-3-mvc-framework/">Spring MVC: Introduction to Spring 3 MVC Framework – Spring 4</a>

<a target="_blank" href="http://crunchify.com/spring-mvc-4-2-2-best-way-to-integrate-js-and-css-file-in-jsp-file-using-mvcresources-mapping/">Spring MVC 4.2.2 – Best way to Add/Integrate JS, CSS and images into JSP file using ‘mvc:resources mapping’</a>

<a target="_blank" href="http://crunchify.com/working-on-spring-mvc-project-how-to-report-list-of-all-loaded-spring-beans-during-startup/">Working on Spring MVC Project? How to Report List of All Loaded Spring Beans during Startup?</a>

<a target="_blank" href="http://crunchify.com/servlet-tutorial-getting-starting-with-jsp-servlet-example/">Servlet Tutorial: Getting Starting with JSP – Servlet Example</a>

<a target="_blank" href="http://crunchify.com/how-to-import-all-spring-mvc-dependencies-to-your-maven-project/">How to import all Spring MVC Dependencies to your Maven Project?</a>

<a target="_blank" href="http://crunchify.com/how-to-update-sparkline-graph-every-3-seconds-in-spring-mvc-realtime-update/">How to Update Sparkline Graph Every 3 Seconds in Spring MVC (Realtime Update)</a>

<a target="_blank" href="http://crunchify.com/spring-mvc-how-to-access-modelmap-values-in-a-jsp/">Spring MVC: How to Access ModelMap Values in a JSP?</a>

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

2015 最簡單的 Spring MVC 入門教程Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips