GrabDuck

Spring 4 MVC Tutorial Maven Example - Spring Java Configuration

:

spring mvc 4 hello world
Spring 4 MVC Tutorial with Eclipse, Maven – Spring 4 MVC is the newer version of our favorite Java MVC framework. A lot has improved in Spring since the Spring 3 MVC. In this tutorial we will create a simple web application from scratch in Eclipse that will use Spring’s latest version 4 MVC framework and Maven configuration. Also we will use Java configuration to configure Spring instead of older XML configuration.

Getting started with Spring 4 MVC Tutorial

1. Create a new Maven project

First things first, we will bootstrap a quick Maven project in Eclipse. Follow these simple steps and create a simple webapplication.

1.1 First in Eclipse go to File -> New and from New project dialog select Maven Project.

spring 4 mvc tutorial eclipse-new-project-wizard

1.2 From New Maven Project dialog, leave the options as shown below and press Next.

spring 4 mvc tutorial eclipse-new-maven-project-dialog

1.3 Now select the project Archetype from the options. Type “web” in the filter text and select maven-archetype-webapp.

eclipse-new-maven-webapp-archetype-project

1.4 As shown below, provide the Group Id and Artifact Id. For this example I have given Group Id net.viralpatel.spring and Artifact Id as HelloWorld.
eclipse-new-maven-project-group-artifact-id

1.5 Once you press Finish, Eclipse should start generating Maven webapp using maven-archetype-webapp. Progress view should show the progress of this step.
eclipse-maven-new-web-archetype-project

New project is created with pom.xml, WebContent folder and src folder.
maven-project-structure-webapp-archetype

2. Add Spring 4 MVC Maven dependencies

Project structure is created. Now let’s start and add first the maven dependencies for Spring 4 MVC in our pom.xml file.

Update pom.xml file and add following dependencies.

pom.xml

After updating pom.xml, Eclipse’s maven plugin should start resolving the dependencies.

3. Set Annotation based Configuration for Spring 4 MVC tutorial

For this Spring 4 MVC tutorial we are going to use Spring’s Java based configuration or annotation based configuration instead of old XML configuration. So now lets add the Java Configuration required to bootstrap Spring 4 MVC example in our webapp.

Create AppConfig.java file under /src folder. Give appropriate package name to your file.

/src/main/java/net/viralpatel/spring/config/AppConfig.java

package net.viralpatel.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.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.viralpatel.spring")
public class AppConfig extends WebMvcConfigurerAdapter {
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");

		return viewResolver;
	}

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

}

AppConfig class is annotated with Spring’s annotations such as @Configuration, @EnableWebMvc and @ComponentScan.

The @Configuration annotation indicates that the class declares one or more @Bean methods. These methods are invoked at runtime by Spring to manage lifecycle of the beans. In our case we have defined @Bean for view resolver for JSP view.

The @EnableWebMvc is equivalent to <mvc:annotation-driven /> in XML. It enables support for @Controller-annotated classes that use @RequestMapping or @GetMapping to map incoming requests to certain methods.

The @ComponentScan annotation is equivalent to <context:component-scan> in XML. It will scan through the given package and register all the Controllers and beans.

The configureDefaultServletHandling() method is overridden and we enable default servlet handler. This will let other http request such as .css, .js slip through the usual DispatcherServlet and let the container process them. So now we can serve the static files css and javascript from our WebApp folder.

The above Annotation based configuration is equivalent to following XML configuration.

4. Set Servlet 3.X Java Configuration

Create AppInitializer class under config package. This class will replace web.xml and it will map the spring’s dispatcher servlet and bootstrap it.

/src/main/java/net/viralpatel/spring/config/AppInitializer.java

package net.viralpatel.spring.config;

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

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

public class AppInitializer implements WebApplicationInitializer {

	public void onStartup(ServletContext container) throws ServletException {

		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(AppConfig.class);
		ctx.setServletContext(container);

		ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));

		servlet.setLoadOnStartup(1);
		servlet.addMapping("/");
	}

}

We have configured the dispatcher servlet using standard Java based configuration instead of the older web.xml. Thus web.xml is no longer required and we can simply delete it.

5. Create the Controller

Create a sample controller HelloController.java under controller package. This will have a simple hello() method that act as starting point. Notice how we have used @GetMapping annotation provided as part of Spring 4 MVC. This is equivalent to @RequestMapping GET.

/src/main/java/net/viralpatel/spring/controller/HelloController.java

package net.viralpatel.spring.controller;

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

@Controller
public class HelloController {

	@GetMapping("/hello")
	public String hello(Model model) {

		model.addAttribute("name", "John Doe");

		return "welcome";
	}
}

6. Create the View and Stylesheet

6.1 Create welcome.jsp file under WEB-INF/views folder. This will be our primary view file.

/src/main/webapp/WEB-INF/views/welcome.jsp

6.2 Next creat the stylesheet for Spring MVC sample.

/src/main/webapp/resources/css/style.css

body {
	background-color: wheat;
}

That’s All Folks

It’s time to execute the project. In Eclipse you can start Tomcat and run the project inside it. Or you can run the project using Embedded Tomcat using Maven.

Once the application starts successfully, launch the browser and open http://localhost:8080/spring4/hello.
spring 4 mvc tutorial

Download Source Code – Spring 4 MVC Tutorial

Source code of this Spring 4 MVC Hello World tutorial is available in Github.