Spring 3 MVC hello world example

In this tutorial, we show you a Spring 3 MVC hello world example, using Maven build tool.
Technologies used :

  • Spring 3.2.13.RELEASE
  • Maven 3
  • JDK 1.6
  • Eclipse 4.4
  • Boostrap 3

1. Project Structure

Download the project source code and review the project folder structure :


spring3-mvc-maven-project.png

2. Maven

A pom.xml template to quick start a Spring MVC project, it defines Spring 3 dependencies, an embedded Jetty container and Eclipse workspace configuration.

pom.xml

<?xml version="1.0"?>
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkyong</groupId>
    <artifactId>spring3-web</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>spring css</name>
    <properties>
        <jdk.version>1.6</jdk.version>
        <spring.version>3.2.13.RELEASE</spring.version>
        <jstl.version>1.2</jstl.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <!-- embedded Jetty server, for testing -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.11.v20150529</version>
                <configuration>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <webApp>
                        <contextPath>/spring3</contextPath>
                    </webApp>
                </configuration>
            </plugin>
            <!-- configure Eclipse workspace -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                    <wtpversion>2.0</wtpversion>
                    <wtpContextName>spring3</wtpContextName>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3. Controller & Mapping

The @RequestMapping has been available since 2.5, but now enhanced to support REST style URLs.

HelloController.java

package com.mkyong.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController { 

    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String printWelcome(ModelMap model) { 
        model.addAttribute("message", "Spring 3 MVC Hello World"); 
        return "hello"; 
    } 
    
    @RequestMapping(value = "/hello/{name:.+}", method = RequestMethod.GET) 
    public ModelAndView hello(@PathVariable("name") String name) { 
        ModelAndView model = new ModelAndView(); 
        model.setViewName("hello"); 
        model.addObject("msg", name); 
        return model; 
    }
}

4. JSP Views

A JSP page to display the value, and include bootstrap css and js.

html4strict

<html lang="en">
 <head></head>
 <body>
  <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
  <spring:url value="/resources/core/css/hello.css" var="coreCss" />
  <spring:url value="/resources/core/css/bootstrap.min.css" var="bootstrapCss" />
  <link href="${bootstrapCss}" rel="stylesheet" />
  <link href="${coreCss}" rel="stylesheet" /> 
  <nav class="navbar navbar-inverse navbar-fixed-top"> 
   <div class="container"> 
    <div class="navbar-header"> 
     <a class="navbar-brand" href="#">Spring 3 MVC Project</a> 
    </div> 
   </div>
  </nav> 
  <div class="jumbotron"> 
   <div class="container"> 
    <h1>${title}</h1> 
    <p> 
     <c:if test="${not empty name}">
       Hello ${name} 
     </c:if> 
     <c:if test="${empty name}">
       Welcome Welcome! 
     </c:if> </p> 
    <p> <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a> </p> 
   </div>
  </div> 
  <div class="container"> 
   <div class="row"> 
    <div class="col-md-4"> 
     <h2>Heading</h2> 
     <p>ABC</p> 
     <p> <a class="btn btn-default" href="#" role="button">View details</a> </p> 
    </div> 
    <div class="col-md-4"> 
     <h2>Heading</h2> 
     <p>ABC</p> 
     <p> <a class="btn btn-default" href="#" role="button">View details</a> </p> 
    </div> 
    <div class="col-md-4"> 
     <h2>Heading</h2> 
     <p>ABC</p> 
     <p> <a class="btn btn-default" href="#" role="button">View details</a> </p> 
    </div> 
   </div> 
   <hr /> 
   <footer> 
    <p>© Mkyong.com 2015</p> 
   </footer>
  </div> 
  <spring:url value="/resources/core/css/hello.js" var="coreJs" />
  <spring:url value="/resources/core/css/bootstrap.min.js" var="bootstrapJs" /> 
  <script src="${coreJs}"></script>
  <script src="${bootstrapJs}"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
 </body>
</html>

5. Spring XML Configuration

5.1 Enable component scanning, view resolver and resource mapping.

spring-web-servlet.xml

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

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  <context:component-scan base-package="com.mkyong.web"/>  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix"> 
      <value>/WEB-INF/views/jsp/</value> 
    </property>  
    <property name="suffix"> 
      <value>.jsp</value> 
    </property> 
  </bean>  
  <mvc:resources mapping="/resources/**" location="/resources/"/>  
  <mvc:annotation-driven/> 
</beans>

5.2 Declares a DispatcherServlet in web.xml. If the Spring XML configuration file is NOT specified, Spring will look for the {servlet-name}-servlet.xml.

In this example, Spring will look for the spring-web-servlet.xml file.

web.xml

<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <display-name>Spring3 MVC Application</display-name>
    <servlet>
        <servlet-name>spring-web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-web</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

You can define a Spring XML file via contextConfigLocation.

web.xml

<?xml version="1.0"?>
<servlet>
    <servlet-name>spring-web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-config.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>spring-web</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

6. Demo

The pom.xml file defines an embedded Jetty container. Issues mvn jetty:run to start the project.
Terminal

$ mvn jetty:run
...
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 10 seconds.

URL : http://localhost:8080/spring3

spring3-mvc-maven-xml-demo.png

URL : http://localhost:8080/spring3/hello/mkyong

spring3-mvc-maven-xml-demo2.png

7. WAR File

To create a WAR file for deployment :
Terminal

your-project$ mvn war:war

A WAR file will be created in project\target\ folder.

${Project}\target\spring3-web-1.0-SNAPSHOT.war
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容