Spring MVC Hello World Example(转)

简介: Spring 3 You may interest at this Spring 3 MVC hello world example. In Spring MVC web application, it consist of 3 standard MVC (Model, Views, C...

 

Spring 3 You may interest at this  Spring 3 MVC hello world example.

In Spring MVC web application, it consist of 3 standard MVC (Model, Views, Controllers) components :

  1. Models – Domain objects that are processed by service layer (business logic) or persistent layer (database operation).
  2. Views – Usually JSP page written with Java Standard Tag Library (JSTL).
  3. Controllers – Interact with service layer for business processing and return a Model.

See following figures 1.1, 1.2 to demonstrate how Spring MVC web application handle a web request.

Figure 1.1 – Image copied from Spring MVC reference with slightly modification.

spring mvc concepts

Figure 1.2 – P.S Image copied from book : Spring Recipes

spring-mvc-concepts-2
Note In Spring MVC , the core disatcher component is the “ DispatcherServlet“, which act as the front-controller (design pattern). Every web request have to go through this “ DispatcherServlet“, and the “DispatcherServlet” will dispatches the web request to suitable handlers.

Spring MVC Tutorial

In this tutorial, you will create a simple Spring MVC hello world web application in order to understand the basic concepts and configurations of this framework.

Technologies used in this tutorial.

  1. Spring 2.5.6
  2. JDK 1.6
  3. Eclipse 3.6
  4. Maven 3

1. Directory Structure

Final directory structure of this tutorial.

spring mvc hello world directory structure
 

2. Dependency library

Spring MVC required two core dependency libraries, spring-version.jar and spring-mvc-version.jar. If you are using JSP page with jstl, include the jstl.jar and standard.jar as well.

File : pom.xml

       <!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>
 
        <!-- Spring MVC framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>2.5.6</version>
	</dependency>
 
	<!-- JSTL --> 
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.1.2</version>
	</dependency>
 
	<dependency>
		<groupId>taglibs</groupId>
		<artifactId>standard</artifactId>
		<version>1.1.2</version>
	</dependency>
 
	<!-- for compile only, your container should have this -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<version>2.5</version>
		<scope>provided</scope>
	</dependency>
 

3. Spring Controller

Spring comes with many Controllers, normally, you just need to extend the AbstractController, if you do not have other special requirement, and override the handleRequestInternal() method and return a ModelAndView object.

File : HelloWorldController.java

package com.mkyong.common.controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
 
public class HelloWorldController extends AbstractController{
 
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
 
		ModelAndView model = new ModelAndView("HelloWorldPage");
		model.addObject("msg", "hello world");
 
		return model;
	}
}
  1. ModelAndView(“HelloWorldPage”) – The “HelloWorldPage” will pass to Spring’s viewResolver later, to indentify which view should return back to the user. (see step 6)
  2. model.addObject(“msg”, “hello world”) – Add a “hello world” string into a model named “msg”, later you can use JSP EL ${msg} to display the “hello world” string.

4. View (JSP page)

In this case, “view” is a jSP page, you can display the value “hello world” that is store in the model “msg” via expression language (EL) ${msg}.

File : HelloWorldPage.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
	<h1>Spring MVC Hello World Example</h1>
 
	<h2>${msg}</h2>
 
</body>
</html>
Note  If the ${msg} is displayed as it is, not the value inside the “msg” model, it may caused by the old JSP 1.2 descriptor, which make the expression languages disabled by default, see the  solution here.

5. Spring Configuration

In web.xml, declared a DispatcherServlet servlet, named “mvc-dispatcher“, and act as the front-controller to handle all the entire web request which end with “htm” extension.

File : web.xml

<web-app id="WebApp_ID" version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
  <display-name>Spring Web MVC Application</display-name>
 
  <servlet>
  	<servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>
                  org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
 	<servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
 
</web-app>
Note  The DispatcherServlet name “ mvc-dispatcher“, is used to defined which file to load the Spring MVC configurations. By default, it will look for file by joining the servlet name “ mvc-dispatcher” with “ -servlet.xml” as the file name, in this case, it will find the “ mvc-dispatcher-servlet.xml” file and load the Spring MVC configuration.

 

Alternatively, you can explicitly specify the Spring configuration file in the “contextConfigLocation” servlet parameter, to ask Spring to load your configurations besides the default “mvc-dispatcher-servlet.xml“.

File : web.xml

<web-app id="WebApp_ID" version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
  <display-name>Spring Web MVC Application</display-name>
 
  <servlet>
  	<servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>
               org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
 	<servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
 
  <context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/SpringMVCBeans.xml</param-value>
  </context-param>
 
  <listener>
        <listener-class>
		org.springframework.web.context.ContextLoaderListener
        </listener-class>
  </listener>
 
</web-app>

6. Spring Beans Configuration

Declared the Spring Controller and viewResolver.

File : mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	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-2.5.xsd">
 
    <bean name="/welcome.htm" 
	class="com.mkyong.common.controller.HelloWorldController" />
 
    <bean id="viewResolver"
    	class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 
</beans>
  1. Controller – Declared a bean name “/welcome.htm” and map it to HelloWorldController class. It means, if an URL with “/welcome.htm” pattern is requested, it will send to the HelloWorldController controller to handle the request.
  2. viewResolver – Define how Spring will looking for the view template. In this case, the controller “HelloWorldController” will return a ModelAndView object named “HelloWorldPage”, and the viewResolver will find the file with following mechanism : “prefix + ModelAndView name + suffix“, which is “/WEB-INF/pages/HelloWorldPage.jsp“.
Note Actually, you don’t need to define the  BeanNameUrlHandlerMapping in the web.xml, by default, if no handler mapping can be found, the DispatcherServlet will creates a BeanNameUrlHandlerMapping automatically. See this article – BeanNameUrlHandlerMapping example for detail.

7. Demo

Run it and access via URL : http://localhost:8080/SpringMVC/welcome.htm , the “SpringMVC” is your project context name.

spring mvc demo

How it works?

  1. http://localhost:8080/SpringMVC/welcome.htm is requested.
  2. URL is end with “.htm” extension, so it will redirect to “DispatcherServlet” and send request to the default BeanNameUrlHandlerMapping.
  3. BeanNameUrlHandlerMapping return HelloWorldController to the DispatcherServlet.
  4. DispatcherServlet forward request to the HelloWorldController.
  5. HelloWorldController process it and return a ModelAndView object named “HelloWorldPage”.
  6. DispatcherServlet received the ModelAndView and call the viewResolver to process it.
  7. viewResolver return the “/WEB-INF/pages/HelloWorldPage.jsp” back to the DispatcherServlet.
  8. DispatcherServlet return the “HelloWorldPage.jsp” back to user.
Spring MVC in annotation You may interest at this  Spring MVC hello world annotation example.

Download Source Code

Download it –  SpringMVC-Hello-World-Example-XML.zip (7KB)
http://www.mkyong.com/spring-mvc/spring-mvc-hello-world-example/
相关文章
|
9天前
|
设计模式 前端开发 Java
步步深入SpringMvc DispatcherServlet源码掌握springmvc全流程原理
通过对 `DispatcherServlet`源码的深入剖析,我们了解了SpringMVC请求处理的全流程。`DispatcherServlet`作为前端控制器,负责请求的接收和分发,处理器映射和适配负责将请求分派到具体的处理器方法,视图解析器负责生成和渲染视图。理解这些核心组件及其交互原理,有助于开发者更好地使用和扩展SpringMVC框架。
24 4
|
27天前
|
前端开发 Java 开发者
Spring MVC中的请求映射:@RequestMapping注解深度解析
在Spring MVC框架中,`@RequestMapping`注解是实现请求映射的关键,它将HTTP请求映射到相应的处理器方法上。本文将深入探讨`@RequestMapping`注解的工作原理、使用方法以及最佳实践,为开发者提供一份详尽的技术干货。
102 2
|
3月前
|
XML Java 应用服务中间件
springMVC01,springMVC的执行流程【第一个springMVC例子(XML配置版本):HelloWorld】
通过一个HelloWorld实例,介绍了SpringMVC的基本概念、执行流程,并详细讲解了如何创建和配置第一个SpringMVC项目(基于XML)。
springMVC01,springMVC的执行流程【第一个springMVC例子(XML配置版本):HelloWorld】
|
2月前
|
JSON 前端开发 Java
SSM:SpringMVC
本文介绍了SpringMVC的依赖配置、请求参数处理、注解开发、JSON处理、拦截器、文件上传下载以及相关注意事项。首先,需要在`pom.xml`中添加必要的依赖,包括Servlet、JSTL、Spring Web MVC等。接着,在`web.xml`中配置DispatcherServlet,并设置Spring MVC的相关配置,如组件扫描、默认Servlet处理器等。然后,通过`@RequestMapping`等注解处理请求参数,使用`@ResponseBody`返回JSON数据。此外,还介绍了如何创建和配置拦截器、文件上传下载的功能,并强调了JSP文件的放置位置,避免404错误。
|
2月前
|
前端开发 Java 应用服务中间件
【Spring】Spring MVC的项目准备和连接建立
【Spring】Spring MVC的项目准备和连接建立
65 2
|
2月前
|
XML 前端开发 Java
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
本文阐述了Spring、Spring Boot和Spring MVC的关系与区别,指出Spring是一个轻量级、一站式、模块化的应用程序开发框架,Spring MVC是Spring的一个子框架,专注于Web应用和网络接口开发,而Spring Boot则是对Spring的封装,用于简化Spring应用的开发。
193 0
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
|
3月前
|
XML 前端开发 Java
springMVC01,【第一个springMVC例子(注解版):HelloWorld】
文章介绍了如何使用注解配置创建第一个SpringMVC项目,并讲解了SpringMVC的执行流程,包括配置web.xml、编写springmvc-servlet.xml配置文件、创建带有@RequestMapping注解的控制器层以及运行测试和执行流程小结。
|
3月前
|
XML 缓存 前端开发
springMVC02,restful风格,请求转发和重定向
文章介绍了RESTful风格的基本概念和特点,并展示了如何使用SpringMVC实现RESTful风格的请求处理。同时,文章还讨论了SpringMVC中的请求转发和重定向的实现方式,并通过具体代码示例进行了说明。
springMVC02,restful风格,请求转发和重定向
|
7月前
|
设计模式 前端开发 JavaScript
Spring MVC(一)【什么是Spring MVC】
Spring MVC(一)【什么是Spring MVC】
|
6月前
|
设计模式 前端开发 Java
【Spring MVC】快速学习使用Spring MVC的注解及三层架构
【Spring MVC】快速学习使用Spring MVC的注解及三层架构
105 1