I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

This is a simple Spring MVC tutorial showing how to set up a Spring MVC project, both with a Java-based configuration as well as with XML configuration.

The Maven dependencies for a Spring MVC project are described in detail in the Spring MVC dependencies article.

2. Spring MVC Using Java Configuration

To enable Spring MVC support through a Java configuration class, all we have to do is add the @EnableWebMvc annotation:

@EnableWebMvc
@Configuration
public class ClientWebConfig {

    /// ...
}

This will set up the basic support we need for an MVC project, such as registering controllers and mappings, type converters, validation support, message converters and exception handling.

If we want to customize this configuration, we need to implement the WebMvcConfigurer interface:

@EnableWebMvc
@Configuration
public class ClientWebConfig implements WebMvcConfigurer {

   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/index");
   }

   @Bean
   public ViewResolver viewResolver() {
      InternalResourceViewResolver bean = new InternalResourceViewResolver();

      bean.setViewClass(JstlView.class);
      bean.setPrefix("/WEB-INF/view/");
      bean.setSuffix(".jsp");

      return bean;
   }
}

In this example, we’ve registered a ViewResolver bean that will return .jsp views from the /WEB-INF/view directory.

Very important here is that we can register view controllers that create a direct mapping between the URL and the view name using the ViewControllerRegistry. This way, there’s no need for any Controller between the two.

If we want to also define and scan controller classes, we can add the @ComponentScan annotation with the package that contains the controllers:

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.baeldung.web.controller" })
public class WebConfig implements WebMvcConfigurer {
    // ...
}

To bootstrap an application that loads this configuration, we also need an initializer class:

public class MainWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(final ServletContext sc) throws ServletException {

        AnnotationConfigWebApplicationContext root = 
          new AnnotationConfigWebApplicationContext();
        
        root.scan("com.baeldung");
        sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet = 
          sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
    }
}

Note that for versions earlier than Spring 5, we have to use the WebMvcConfigurerAdapter class instead of the interface.

3. Spring MVC Using XML Configuration

Alternatively to the Java configuration above, we can also use a purely XML config:

<context:component-scan base-package="com.baeldung.web.controller" />
<mvc:annotation-driven />    

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

    <mvc:view-controller path="/" view-name="index" />

</beans>

If we want to use a purely XML configuration, we’ll also need to add a web.xml file to bootstrap the application. For more detail on this approach, check out our previous article.

4. Controller and Views

Let’s have a look at an example of a basic controller:

@Controller
public class SampleController {
	@GetMapping("/sample")
    public String showForm() {
        return "sample";
    }

}

And the corresponding jsp resource is the sample.jsp file:

<html>
   <head></head>

   <body>
      <h1>This is the body of the sample view</h1>	
   </body>
</html>

The JSP based view files are located under the /WEB-INF folder of the project, so they’re only accessible to the Spring infrastructure and not by direct URL access.

5. Spring MVC with Boot

Spring Boot is an addition to Spring Platform which makes it very easy to get started and create stand-alone, production-grade applications. Boot is not intended to replace Spring, but to make working with it faster and easier.

5.1. Spring Boot Starters

The new framework provides convenient starter dependencies – which are dependency descriptors that can bring in all the necessary technology for a certain functionality.

These have the advantage that we no longer need to specify a version for each dependency but instead allow the starter to manage dependencies for us.

The quickest way to get started is by adding the spring-boot-starter-parent pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>

This will take care of dependency management.

5.2. Spring Boot Entry Point

Each application built using Spring Boot needs merely to define the main entry point. This is usually a Java class with the main method, annotated with @SpringBootApplication:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

This annotation adds the following other annotations:

  • @Configuration – which marks the class as a source of bean definitions
  • @EnableAutoConfiguration – which tells the framework to add beans based on the dependencies on the classpath automatically
  • @ComponentScan – which scans for other configurations and beans in the same package as the Application class or below

With Spring Boot, we can set up frontend using Thymeleaf or JSP’s without using ViewResolver as defined in section 3. By adding spring-boot-starter-thymeleaf dependency to our pom.xml, Thymeleaf gets enabled, and no extra configuration is necessary.

The source code for the Boot app is, as always, available over on GitHub.

Finally, if you’re looking to get started with Spring Boot, have a look at our reference intro here.

6. Conclusion

In this example we configured a simple and functional Spring MVC project, using Java configuration.

The implementation of this simple Spring MVC tutorial can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.

When the project runs locally, the sample.jsp can be accessed at http://localhost:8080/spring-mvc-java/sample.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Sujit Tripathy
Guest
Sujit Tripathy

Thanks for the post. I am wondering this when addViewControllers will be helpful? Will it be when there is no business logic between view and another view layer so that the action and view mapping can be done via the ViewControllerRegistry. I think we can get the with @controller also so is there any added advantage on this? share your thoughts.

Eugen Paraschiv
Guest

Hey Sujit,
Yes, that’s the general idea. You can certainly handle all of these mappings in the Controller layer, but if there’s no extra logic, it’s generally easier to do everything here and not have to define lots of extra methods with no real logic.
Hope that clarifies things. Cheers,
Eugen.

Sujit Tripathy
Guest
Sujit Tripathy

Thanks Eugen.