Spring MVC Hello World Example (GO)

Source: Internet
Author: User
Tags spring mvc tutorial

Spring 3Interest at thisSpring 3 MVC Hello World example.

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

    1. Models–domain objects that is processed by service layer (business logic) or persistent layer (database operation).
    2. Views–usually JSP page written with the 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

NoteIn Spring MVC, the core Disatcher component is the " Dispatcherservlet", which act as the Front-controller (design pattern). Every Web request has to go through this " Dispatcherservlet", and the" Dispatcherservlet "would dispatches the Web request to suitable handlers. Spring MVC Tutorial

In this tutorial, you'll create a simple Spring MVC Hello World Web application on order to understand the basic concept s 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, dependency libraries, Spring-version.jar and Spring-mvc-version.jar. If is using JSP page with Jstl, include the Jstl.jar and Standa Rd.jar as well.

File:pom.xml

       <!--Spring Framework--<dependency><groupid>org.springframework</groupid><artifactid >spring</artifactId><version>2.5.6</version></dependency>  <!--spring MVC Fram Ework-<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 has this--><dependency><groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid><version>2.5</version><scope>p rovided</scope></dependency> 
3. Spring Controller

Spring comes with many Controllers, normally, you just need to extend AbstractController the and if you does not has other special requ Irement, 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{  @Overrideprotected Modelandview handlerequestinternal (httpservletrequest request, HttpServletResponse response) throws Exception { modelandview model = new Modelandview ("Helloworldpage"); Model.addobject ("msg", "Hello World");  return model;}} 
    1. Modelandview ("Helloworldpage") , haven "Helloworldpage" would pass to Spring's viewresolver later, to indentify which view should return back to the US Er. (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" s Tring.
4. View (JSP page)

The "View" is a JSP page, and you can display the value ' Hello World ' that's store in the Model "MSG" via Expressio N Language (EL) ${msg}.

File:HelloWorldPage.jsp

<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>
Note If the ${msg} is displayed as it was, not the value inside the "MSG" model, it could caused by the old JSP 1.2 descriptor, WH Ich make the expression languages disabled by default and see thesolution here . 5. Spring Configuration

web.xml in, 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 would look for file by joining the servlet name "Mvc-dispatcher"With"-servlet.xml"As the file name, in this case, it'll find the"Mvc-dispatcher-servlet.xmlFile and load the Spring MVC configuration.

Alternatively, you can explicitly specify the Spring configuration file in the "contextconfiglocation" servlet pa Rameter, 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.ser Vlet. Dispatcherservlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet>&  nbsp <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 a URL with "/welcome.htm" pattern is requested, it'll send to the Helloworldcontroller controller to Handl e the request.
    2. Viewresolver –define How Spring would looking for the view template. In this case, the controller "Helloworldcontroller" would return a Modelandview object named "Helloworldpage", and the View Resolver would find the file with following mechanism: "prefix + modelandview name + suffix", which "/web- Inf/pages/helloworldpage.jsp".
NoteActually, you don ' t need to define the beannameurlhandlermapping in the Web. XML, by default, if no handler mapping can be found, the Dispatcher Servlet would 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'll redirect to ' Dispatcherservlet ' and send request to the default Beannameurlha Ndlermapping.
    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" to the user.
Spring MVC in annotationInterest at thisSpring MVC Hello World annotation example.Download Source codedownload it–springmvc-hello-world-example-xml.zip (7KB) http://www.mkyong.com/spring-mvc/spring-mvc-hello-world-example/

Spring MVC Hello World Example (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.