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

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

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.

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.

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/

时间: 2024-12-28 11:59:41

Spring MVC Hello World Example(转)的相关文章

Swagger+ springfox +Spring mvc

简介 Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步.Swagger 让部署管理和使用功能强大的API从未如此简单.这一次我将从零开始搭建一个工程来演示如何在Spring mvc中整合Swagger生成Restful接口文档. 新建工程 我们新建一个Maven工程,并添加Web Facet,工程结构如下图所

视图框架:Spring MVC 4.0(1)

目录 一.表单标签库 1.1.简介 1.2.常用属性 1.3.form标签与input标签 1.4.checkbox标签 1.5.radiobutton标签 1.6.password标签 1.7.select标签 1.8.option标签 1.9.options标签 1.10.textarea.errors标签 1.11.hidden标签 1.12.radiobuttons 单选列表与checkboxs复选列表 二.视图解析器 2.1.ViewResolver视图解析器 2.2.链式视图解析器

Spring MVC HTTP请求数据绑定

package com.springmvc.controller; import com.springmvc.model.UserInfo; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; import org.springframework.uti

关于spring mvc的配置文件

1. Web.xml <!--配置页面控制器--> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</par

[转] 使用Spring MVC构建REST风格WEB应用

原文地址:http://fancy888.iteye.com/blog/1629120 对于运行在网络上的MIS系统而言,处理数据的是整个系统的主要任务,翻开程序我们可以看到,80%以上的代码都在处理数据的CRUD操作.采用一种什么样的框架结构,能够使得处理数据的操作变得简单且易理解,这是大部分开发者尤其是架构设计者一直以来思考的一个问题. REST(Representational State Transfer)是一种编程风格,特别是针对网络应用的设计和开发,采用REST可以显著降低开发的复杂

Spring MVC 基础

Spring MVC 基础 1.Web MVC基础 MVC的本质是表现层模式,我们以视图模型为中心,将视图和控制器分离出来.就如同分层模式一样,我们以业务逻辑为中心,把表现层和数据访问层代码分离出来是一样的方法.框架只能在技术层面上给我们帮助,无法在思考和过程上帮助我们,而我们很多人都不喜欢思考和尝试. 2.实现Web MVC的基础 实现Web MVC基础可以概括为1个前段控制器和2个映射. (1)前端控制器FrontController ASP.NET和JSP都是以Page路径和URL一一对应

spring MVC学习(一)---前端控制器

1.spring MVC中的前段控制器就是DsipatcherServlet,它在spring MVC框架中的结构图如下: 2.DispatcherServlet其实就是一个Servlet,它继承了HttpServlet这个抽象类. 先来看下该类在的位置: 为了使用它,你需要在你的web应用程序中的web.xml中配置一下,配置如下: <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class&

搭建基于spring MVC框架 + RESTful架构风格技术总结

实战篇: 在SpringMVC框架中搭建RESTful架构风格来完成客户端与服务器端的低耦合度.可扩展性.高并发与大数据流量的访问. 用RESTful架构的创建步骤: 1.创建一个全新的Web工程 2.导包,导入所需要的所有第三方jar包.(springMVC+Hibernate的基本包是必须的) 3.作配置,针对不同的项目需求和不同的搭建设计,开发人员可以按照自己的编码风格来设计符合项目开发具体 应该用多少篇配置文件.但是这几篇配置文件是必不可少的: 3-1.web.xml配置文件:最基本的配

Spring MVC简介

Spring MVC框架是有一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC和Struts.Struts2非常类似.Spring MVC的设计是围绕DispatcherServlet展开的,DispatcherServlet负责将请求派发到特定的handler.通过可配置的handler mappings.view resolution.locale以及theme resolution来处理请求并且

Spring MVC 学习笔记(二):@RequestMapping用法详解

一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.xml中配置 <servlet>     <servlet-name>servletName</servlet-name>     <servlet-class>ServletClass</servlet-class> </servlet>