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.

<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

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

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

package com.crunchify.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; /*
*
*/ @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.

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

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

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.

MVC实现(简单小例子)的更多相关文章

  1. php+jquery+ajax+json简单小例子

    直接贴代码: <html> <title>php+jquery+ajax+json简单小例子</title> <?php header("Conte ...

  2. C#利用事件与委托进行窗体间传值简单小例子

    本篇博客是利用C#委托与事件进行窗体间传值的简单小例子 委托与事件的详细解释大家可以参照张子阳的博客: http://www.tracefact.net/CSharp-Programming/Dele ...

  3. ASP.NET Cookie对象到底是毛啊?(简单小例子)

    记得刚接触asp.net的时候,就被几个概念搞的头痛不已,比如Request,Response,Session和Cookie.然后还各种在搜索引擎搜,各种问同事的,但是结果就是自己还是很懵的节奏. 那 ...

  4. 关键字Lock的简单小例子

    一.什么是Lock? Lock——字面上理解就是锁上:锁住:把……锁起来的意思: 为什么要锁?要锁干什么?——回到现实中可想象到,这个卫生间我要上,其他人不要进来!(所以我要锁住门):又或者土味情话所 ...

  5. 详细解读Android中的搜索框(一)—— 简单小例子

    这次开的是一个讲解SearchView的栏目,第一篇主要是给一个小例子,让大家对这个搜索视图有一个了解,之后再分布细化来说. 目标: 我们先来定个目标,我们通过搜索框来输入要搜索的联系人名字,输入的时 ...

  6. spring+spring mvc+JdbcTemplate 入门小例子

    大家使用这个入门时候 最好能够去 搜一下 spring mvc 的 原理,我放一张图到这里,自己琢磨下,后面去学习就容易了 给个链接 (网上一把,千万不能懒)    https://www.cnblo ...

  7. 关于ExpandableListView用法的一个简单小例子

    喜欢显示好友QQ那样的列表,可以展开,可以收起,在android中,以往用的比较多的是listview,虽然可以实现列表的展示,但在某些情况下,我们还是希望用到可以分组并实现收缩的列表,那就要用到an ...

  8. SpringMVC静态文件(图片)访问+js访问 简单小例子

    项目文件布局: web.xml文件: <?xml version="1.0" encoding="UTF-8"?> <web-app vers ...

  9. Ajax的简单小例子

    1.首先下载ajax.dll,一个百度一下都有下载的!自行查找. 2.把ajax.dll导入到工程.右键工程-->添加引用--->浏览,找到下载好的ajax.dll文件,点击确定,这时候在 ...

随机推荐

  1. Openssl 生成证书server.key and server.crt

    1.key的生成 openssl genrsa -des3 -out server.key 2048 这样是生成rsa私钥,des3算法,openssl格式,2048位强度.server.key是密钥 ...

  2. Pyhton爬虫实战 - 抓取BOSS直聘职位描述 和 数据清洗

    Pyhton爬虫实战 - 抓取BOSS直聘职位描述 和 数据清洗 零.致谢 感谢BOSS直聘相对权威的招聘信息,使本人有了这次比较有意思的研究之旅. 由于爬虫持续爬取 www.zhipin.com 网 ...

  3. CS Round#53 C Histogram Partition

    题意:给定一个数组A,以及一个初始值全为0的空数组B,每次可以对数组B的任意一个区间内的所有数+x,问至少几次操作能把B数组变成A数组 NOIP原题(积木大赛)升级版,话说CS怎么那么多跟NOIP原题 ...

  4. 大白话Vue源码系列(02):编译器初探

    阅读目录 编译器代码藏在哪 Vue.prototype.$mount 构建 AST 的一般过程 Vue 构建的 AST 题接上文,上回书说到,Vue 的编译器模块相对独立且简单,那咱们就从这块入手,先 ...

  5. 以css伪类为基础,引发的选择器讨论 [新手向]

    作为第一篇技术干货,来写哪个方面的内容,我着实考虑了很久. 经过了整整30秒的深思熟虑,我决定就我第一次发现新大陆一样的内容,来进行一次讨论. 伪类:伪类对元素进行分类是基于特征(characteri ...

  6. reverse函数实现指定页面跳转

    需求: 在views中返回的url需要返回到具体的某一篇文章的评论列表 return redirect(reverse('cms_comment_manage',args=(number,))) dj ...

  7. TextMesh Pro Emoji Align With Text(表情和文字对齐)

    前言 MMO游戏中需要富文件组件,大体功能包括图文混排,表情,超链接,文字动画等富文本功能,且DC数占用少. 本文选择Unity免费提供的TextMesh Pro 解决方案. 软件环境 Unity3D ...

  8. 使用Spring访问Mongodb的方法大全——Spring Data MongoDB查询指南

    1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...

  9. 自学Python2.6-深浅拷贝

    Python 深浅拷贝 一.深浅拷贝- 数字.字符串 对于 数字 和 字符串 而言,赋值.浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址. import copy n1=123 n2=n1 # # ...

  10. Ubuntu 下使用 ZTE ME3630 4G 模块

    之前在 AM5728 开发板上使用过这个模块,用来在野外采集数据上传到服务器.最近接触另外一个项目,做一个演示用的样机,需要移动的,也是采用了这个模块来上传数据.样机环境是 Ubuntu 16.04 ...