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.

Download – spring4-mvc-example.zip (6.54 KB)
Get our Articles via Email. Enter your email address.

You may also like...

22 Comments

  1. Nodine says:

    Hello,
    Thank you for this usefull tutorial.
    Juste a question please, why do you put “spring4” in the test URL ? http://localhost:8080/spring4/hello.

    Best Regards
    Nordine

    • Eddie says:

      The example is run under maven tomcat 7 plugin:

      org.apache.tomcat.maven
      tomcat7-maven-plugin

      /spring4

      You can check it out in pom.xml and the above link Embedded Tomcat using Maven.
      If you build it at war and deploy to a standalone tomcat instance, you need to use the war name as context

      Thanks
      Eddie

  2. Nilesh says:

    Hello,
    This tutorial is not working for me. Can you tell me why did you put “spring” in the test URL and not the actual context name?

    Thanks,
    Nilesh

  3. Sucheta Hardikar says:

    I have copied your complete project for Spring MVC. But value of name mapped through Model object is not accessible in the JSP view. I tried with ELIgnored attribute , by enableing EL by using page directive in the JSP. But still value of name is not accessible through JSP . What is the reason ?

    • pape says:

      try with instead of ${name}

    • pape says:

      try with c:out value=”${name}”

  4. Aegis says:

    You need to include spring taglibs in the jsp to get the mapping correct.

  5. Anjul Goel says:

    Hi Sucheta,

    The reason the name is not accesible is because you are using an old JSP 1.2 descriptor. Look out for the solution is the below link. https://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el/

  6. Geetha says:

    Hello Sir, Thanks for sharing, Good Work.

  7. Sandeep says:

    Could you please tell me why css is not loading in jsp. I am not able to see background color.

    • SANTOSH says:

      file should be in src\main\webapp\resources\css\style.css by default resources folder is NOT under webapp.

  8. Good Post

  9. Mr-Genius says:

    It is very good information for programmers who begin near days. Thanks big!

  10. Prem says:

    How to make it work .. Home Page works .. .but mapping to hello is not working … Even tried XML based also not able to get the mapping right … any wsy to debug where is the exact issue … Mapping to particular JSP view does not work for mw ..

    • nitin says:

      @GetMapping(“/”)
      public String hello(Model model) {
      change the mapping in controller

  11. xxxx says:

    place resource under the directory [webapp]

  12. Anjani says:

    I am getting a problem regarding these code that HTTP Status 404 – /helloworld/

  13. Raj says:

    Thank you. it worked.
    -Raj

  14. Sakthivel says:

    Can you give solution for the below blog? Web module can be done by child developer. While dealing with EAR, facing lot of issues.

    http://stackoverflow.com/questions/42818621/hibernate-configuration-from-ejb-module-returns-illegalstateexception-in-my-ear

  15. bods says:

    the home page works , but mapping helloworld/hello is giving 404 error , i am using tomcat 8 and adding the server in eclipse and then choosing run on server .
    any help where am i going wrong

  16. Annamalai T says:

    Nice Tutorial

  17. Rajesh K says:

    Nice tutorial, but when i hit the url “http://localhost:8080/springrest/customers” i’m getting “HTTP Status 404 – /springrest/customers”. Please help me in this.

Leave a Reply

Your email address will not be published. Required fields are marked *