Spring 4 MVC Hello World Tutorial – Full Example

44 Flares Twitter 3 Facebook 8 Google+ 33 LinkedIn 0 Filament.io 44 Flares ×

In this tutorial you will learn how to develop a Spring 4  MVC Hello world example. We hope this tutorial will give you a quick start with Spring MVC development using the latest Spring 4 Release.

Technologies used:

  • Spring 4.0.1.RELEASE
  • JDK 1.6
  • Maven 3
  • Eclipse Java EE IDE ( Eclipse JUNO)

Updates (10 -Feb -2014): Updated the tutorial with JavaConfig. Now explains how to use WebApplicationInitializer and @Configuration 

Part 1: Maven Project Setup In Eclipse

Let us start with the creation of  a Maven web project in Eclipse. A maven web project archetype will create all the necessary folder structures required for a web project. We assume that you have installed the maven plugins for Eclipse. If you haven’t configured it, refer our earlier Spring tutorial that has section explaining how to setup maven in eclipse.

File ->  New  -> Other -> Maven -> Maven Project

Maven Project Eclipse

Click Next and Click Next again ( If you wish to change default Workspace location , you may do so). In the next screen you should pick the maven web app archetype. Refer the screen below

Maven Web App Archetype

Click Next  and provide the following values

  1. GroupId :com.javahash.web ( you can change this according to your package structure)
  2. Artifact Id: Spring4MVCHelloWorld
  3. Version: 1.0-SNAPSHOT

Click Finish to complete the Project Setup.

Project Structure-SpringMVC

Part 2:  Spring Configuration

We now need to add the spring framework libraries as dependencies in mavan (pom.xml).  For the sake of ease, we are going to define a maven variable to hold the spring framework version. If we need to change to a different spring release only this variable needs to be changed.

Dependencies – pom.xml

<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/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.javahash.web</groupId>
 <artifactId>Spring4MVCHelloWorld</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>Spring4MVCHelloWorld Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
 <spring.version>4.0.1.RELEASE</spring.version>
 </properties>
 <dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 <!-- Spring dependencies -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>${spring.version}</version>
 </dependency>

 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring.version}</version>
 </dependency>

 </dependencies>
 <build>
 <finalName>Spring4MVCHelloWorld</finalName>
 </build>
</project>

Spring Beans Configuration

We need a configuration file that holds the spring configuration information. In this tutorial we will be using the Spring’s auto scan feature ( annotation) to detect and initialize beans. We can name this configuration file any name. We are using the name dispatcher-servlet.xml for this project.


<beans xmlns="http://www.springframework.org/schema/beans"
 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-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:component-scan base-package="com.javahash.spring.controller" />

 <bean
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix">
 <value>/WEB-INF/views/</value>
 </property>
 <property name="suffix">
 <value>.jsp</value>
 </property>
 </bean>
</beans>

We have told spring to look at the package com.javahash.spring.controller for the beans and we have also told the framework that all views are kept under WEB-INF/views folder.

Part 3 : Web App Configuration

Next step is to configure the web app so that it uses Spring’s DispatcherServlet as the Front Controller.
Configuring web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<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>Archetype Created Web Application</display-name>

 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>

 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
 </context-param>

 <listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>
</web-app>

Part 4: Controller Development

From Spring 3 on wards there exists excellent support for annotations. We will use annotations to  mark our class as  a controller in the standard MVC design. The HelloWorldController is a very simple controller that just echoes a message. It takes a parameter and just echoes it.


package com.javahash.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

@RequestMapping("/hello")
 public String hello(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
 model.addAttribute("name", name);
 return "helloworld";
 }

}

Please note the use of @Controller and @RequestMapping . The URL takes a parameter with name “name”.

View

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring4 MVC -HelloWorld</title>
</head>
<body>
<h1>Hello : ${name}</h1>
</body>
</html>

We can generate a War file and deploy that to a web server to test the application. In eclipse , right click the project and Click Run As – > Maven Install. This will build the project and create a war file in the target folder. In the case of this example the file will be Spring4MVCHelloWorld.war

Deploy this WAR file to a web server , say Tomcat and issue

http://localhost:8080/Spring4MVCHelloWorld/hello/?name=JavaHash

Results

How to Avoid XML Files and use JavaConfig

Maintaining configuration using XML has its advantages and disadvantages. If you are not a fan of XML configuration and wish to enjoy the benefits of annotations based configuration, you can do so easily in Spring. It is your choice to go the XML path or the JavaConfig path. JavaConfig is a cool approach and helps in rapid application development and provides easy maintenance. When the number of artifacts in the project increases, JavaConfig is very handy. Also it is the developer friendly means of handling configuration. Let us see how we can replace the dispatcher-servlet.xml and the Spring Configuration defined in the web.xml to  Java classes using JavaConfig.

Replacing dispatcher-servlet.xml with Java File


package com.javahash.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration //Marks this class as configuration
//Specifies which package to scan
@ComponentScan("com.javahash.spring")
//Enables Spring's annotations
@EnableWebMvc
public class Config {

 @Bean
 public UrlBasedViewResolver setupViewResolver() {
 UrlBasedViewResolver resolver = new UrlBasedViewResolver();
 resolver.setPrefix("/WEB-INF/views/");
 resolver.setSuffix(".jsp");
 resolver.setViewClass(JstlView.class);
 return resolver;
 }
}

Moving Spring Configuration from web.xml to WebApplicationInitializer


package com.javahash.spring.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInitializer implements WebApplicationInitializer {

public void onStartup(ServletContext servletContext) throws ServletException {

 AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
 ctx.register(Config.class);

 ctx.setServletContext(servletContext);

 Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
 servlet.addMapping("/");
 servlet.setLoadOnStartup(1);

 }

}

Download Source Code

Download – Project Source Code

References

Spring 4

Share this post:

Related Posts

  • https://twitter.com/a2xchip Alexander Chip

    Cool tutorial. I think about learning Java/Spring about a year. It is really cool.

  • Matthieu Bertin

    Why did you choose to use xml files for the configuration?

    • http://pickadvice.com/ prem kumar

      I have updated the tutorial with JavaConfig also. It is up-to the developer to choose which way they want to go. I have outlined both approaches in this update.

  • Edgar Miguel Mamani Condori

    Where do I find javax.servlet.ServletRegistration.Dynamic?

    • Edgar Miguel Mamani Condori

      Ok, the artifact is:

      javax.servlet
      javax.servlet-api
      3.0.1

      • http://pickadvice.com/ prem kumar

        Thanks for this information.

  • Douglas Crews

    Helpful++

  • dev

    I am not sure how were you able to run your code, you specify the version of spring as 4.0.1; however your xml context file says spring-beans 3.0 version…

    • http://pickadvice.com/ prem kumar

      That is the XML schema definition. It will work with spring 3 and 4.

  • Bogdan Marian Oloeriu

    This is confusing for someone new to spring. Can you please split this
    in 2 related tutorials? One based on xml configuration and one based on
    java configuration. I’m not able to see what file goes where in what
    package or folder and how the final project structure should look like.

    • http://pickadvice.com/ prem kumar

      Sure. I will organize it better.

  • Chris Kalubi

    My IDE (intelliJ) doesn’t recognize the register() method int the webInitializer class:
    ctx.register(Config.class);
    it’s strange because I have spring-web.jar in my dependecies.
    Do you know why?

  • ahmed abbas

    very helpful thanks

  • Brandon

    Hi there, Is it possible for you to provide a link for the code to be downlaoded?

    • http://pickadvice.com/ prem kumar

      I will provide the code in a week. Right now I am out of station and once iam back I will provide you the full code.

      • http://pickadvice.com/ prem kumar

        The article is updated with the link to download the complete project source code.

  • sandeep singh

    Hi ,
    Is it possible for you to provide a link for the code to be downlaoded?

    • http://pickadvice.com/ prem kumar

      Complete project source code is now available. Please check the Download section of the article.

      • sandeep

        thnx 4 source code.
        “http://localhost:8080/Spring4MVCHelloWorld/” is working
        but whn I fired “http://localhost:8080/Spring4MVCHelloWorld/hello/?name=JavaHash” URL that is not working it gives me 404 error.

        • DBspringing

          remove the / before the ?

  • DBspringing

    I swapped the xml for JavaConfig. Now when I run the output on the browser is

    Hello : ${name}

    What am I missing?

  • Seetesh

    Does this code run on JBoss 7.1.1? Pls try to deploy it as most of us wont use Tomcat to deploy the same. Besides you have not mentioned which
    Tomcat version it has been tested.

    • http://pickadvice.com/ prem kumar

      It should run on jboss. There is nothing tomcat specific in the code. Use maven to build the project and add all dependencies in pom.XML. I used Tomcat 7

  • Rex Rao

    Does this code work on JBoss 7.1.1?

    • http://pickadvice.com/ prem kumar

      It is just spring and jsp.it should work in jboss.