http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/ 非常棒的spring入门,maven,以及eclipse

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

Last Updated on 9 September, 2016  by  App Shah 285 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 – Let’s Setup Environment

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

  1. Tomcat 8.0.37 – Download latest Apache Tomcat from this link.
  2. Make sure you download Eclipse IDE for Java EE Developers (Neon v4.6) – Download link. (diagram below)
  3. Spring 4.3.1 (No download required) – we will use Maven dependency.
  4. JDK 1.8 – Download link.

Make sure you download Java EE:

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

Here is a final result: Welcome page ==> index.jsp

Result returns from Controller Class ??

Now Let’s get started on Tutorial

Step-1

  • Open Eclipse
  • Create New Eclipse Workspace – This is must to avoid any existing workspace config issue.

Step-2

  • Click on File
  • Click on New
  • Choose Dynamic Web Project
  • One popup window, Provide Project Name: CrunchifySpringMVCTutorial
  • Make sure you use Target Runtime as Apache Tomcat 8.0. If you don’t see Target Runtime then follow these steps.

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. Make sure you update Java version to 1.7 if you haven’t yet moved to JDK 1.8.

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

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

<build>

<sourceDirectory>src</sourceDirectory>

<plugins>

<plugin>

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

<version>3.1</version>

<configuration>

<source>1.8</source>

<target>1.8</target>

</configuration>

</plugin>

</plugins>

</build>

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.3.1.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aop</artifactId>

<version>4.3.1.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>4.3.1.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>4.3.1.RELEASE</version>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

</dependencies>

</project>

Step-5

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

Create new file web.xml. 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.

  • Right click on Java Resources -> src
  • Click New -> 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 new file /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 another file /WebContent/WEB-INF/jsp/welcome.jsp.

NOTE: Don’t forget to create jsp folder and put welcome.jsp inside that ??

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

  • If you don‘t see Tomcat Server in Servers tab then follow steps to add Apache Tomcat to Eclipse.
  • 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.

Hurray.. 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 – Having HTTP Status 404 error?

时间: 2024-10-03 00:39:24

http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/ 非常棒的spring入门,maven,以及eclipse的相关文章

spring mvc 注解扫描问题 ,扫描不到controller, use-default-filters=&quot;false&quot;

今天搭了个spring mvc项目,怎么也扫描不到controller,最后发现问题在use-default-filters="false"上面,乱copy出的问题 (默认值是true,它的作用就是扫描一些相关的注解,包括了@controller,@Component,@Service,@Repository等,) <context:component-scan base-package="com.example" use-default-filters=&q

MVC模式(Model View Controller)下实现数据库的连接,对数据的删,查操作

MVC模式(Model View Controller): Model:DAO模型 View:JSP  在页面上填写java代码实现显示 Controller:Servlet 重定向和请求的转发: 若目标的相应页面不需要从request里面读取任何信息,则可以使用重定向,可以防止表单重复提交: ------------------------------------------------------------------------------------------------ Stude

Model View Controller(MVC) in PHP

The model view controller pattern is the most used pattern for today’s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based

spring MVC 管理HttpClient---实现在java中直接向Controller发送请求

在spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在java代码中直接向controller发送请求,这时可以使用HttpCilent实现. 首先用到的包是httpclient-4.3.5.jar和httpcore-4.3.2.jar 先看下面代码: package module.system.common; import java.io.IOException; import java.util.ArrayList; import

spring mvc DispatcherServlet详解之二---request通过Controller获取ModelAndView

整个spring mvc的架构如下图所示: 上篇文件讲解了DispatcherServlet通过request获取控制器Controller的过程,现在来讲解DispatcherServletDispatcherServlet的第二步:通过request从Controller获取ModelAndView. DispatcherServlet调用Controller的过程: DispatcherServlet.java doService()--->doDispatch()--->handler

Spring MVC 向页面传值-Map、Model和ModelMap

除了使用ModelAndView方式外.还可以使用Map.Model和ModelMap来向前台页面创造 使用后面3种方式,都是在方法参数中,指定一个该类型的参数.例如: Java代码 1 @RequestMapping("/test") 2 public String test(Map<String,Object> map,Model model,ModelMap modelMap){ 3 4 map.put("names", Arrays.asList

MVC(Model.view,Controller)

(一)MVC javabean :符合某种规范的java组件,也就是java类 Model 模型,操作数据的业务处理层,并独立于表现层. View 视图,通过客户端数据类型显示数据,并回显模型层的执行结果. Conroller 控制器.视图层和模型层的桥梁,控制数据的流向,接受视图层发出的事件,并重绘视图. [个人理解:mvc设计模式当中,Model是模型层,用于管理数据,操作数据,View是视图层,是页面显示后的效果,Conroller是控制层,用来控制执行怎样的操作,例如增删改查,然后执行成

Spring MVC 4.2.2 中最好的集成静态资源的方法

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

Spring MVC 3 深入总结

一.前言: 大家好,Spring3 MVC是非常优秀的MVC框架,由其是在3.0版本发布后,现在有越来越多的团队选择了Spring3 MVC了.Spring3 MVC结构简单,应了那句话简单就是美,而且他强大不失灵活,性能也很优秀. 官方的下载网址是:http://www.springsource.org/download   (本文使用是的Spring 3.0.5版本) Struts2也是比较优秀的MVC构架,优点非常多比如良好的结构.但这里想说的是缺点,Struts2由于采用了值栈.OGNL