Spring MVC Tutorial

This is a simple Spring MVC tutorial. In this post, we will learn as how to set up a Spring MVC project. We will perform the setup using following options

  1. XML based Configurations
  2. Java-based Configurations
  3. Spring Boot

 

1. DispatcherServlet 

Spring MVC, like many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing while actual work is performed by configurable, delegate components.

We have the options to provide these configurations using XML or Java based configurations.

 

1.1 The web.xml

Below is an example of web.xml configuration to register and initialize the DispatcherServlet.

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/app-context.xml</param-value>
   </context-param>
   <servlet>
      <servlet-name>spring-mvc-app</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value />
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>spring-mvc-app</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>
</web-app><code>

 

1.2 The Java Configurations

Below is an example of the Java configuration that registers and initializes the DispatcherServlet.

public class DemoWebApplicationInitializer implements WebApplicationInitializer {

 @Override
 public void onStartup(ServletContext servletCxt) {

  // Load Spring web application configuration
  AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
  ac.register(AppConfig.class);
  ac.refresh();

  // Create and register the DispatcherServlet
  DispatcherServlet servlet = new DispatcherServlet(ac);
  ServletRegistration.Dynamic registration = servletCxt.addServlet("spring-mvc-app", servlet);
  registration.setLoadOnStartup(1);
  registration.addMapping("/*");
 }
}

[pullquote align=”normal”]Read our article to get more detail about the multiple approaches to configure a Spring MVC project [/pullquote]

 

2. Spring MVC Configurations

Let’s have a look at some configurations points required for Spring MVC project setup.

 

2.1 View Resolvers

@EnableWebMvc
@Configuration
public class AppConfig implements WebMvcConfigurer {

 @Bean
 public ViewResolver getViewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/views/");
  resolver.setSuffix(".jsp");
  return resolver;
 }
}

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.javadevjournal" />    
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/view/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
  </bean>
</beans>

 

2.1 View Technologies

Using view technologies in Spring MVC is pluggable, whether you use Thymeleaf, Groovy Markup Templates, JSPs, or other, is primarily a matter of a configuration change. To register view technology of choice, we need to register correct ViewResolver.

@EnableWebMvc
@Configuration
public class AppConfig implements WebMvcConfigurer {

 @Override
 public void configureViewResolvers(ViewResolverRegistry registry) {
  registry.freemarker();
 }

 // Configure FreeMarker...
 @Bean
 public FreeMarkerConfigurer freeMarkerConfigurer() {
  FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
  configurer.setTemplateLoaderPath("/WEB-INF/freemarker");
  return configurer;
 }
}

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

<mvc:view-resolvers>
    <mvc:freemarker/>
</mvc:view-resolvers>
<!-- Configure FreeMarker... -->
<mvc:freemarker-configurer>
    <mvc:template-loader-path location="/WEB-INF/freemarker"/>
</mvc:freemarker-configurer>

 

3. Spring MVC Configurations

The view technologies in Spring MVC is pluggable. We can use JSP, Thymeleaf or Freemarker to render the view.

 

3.1 JSP View

Let’s create a simple HTML(greeting.jsp) for our view and store it under the /WEB-INF directory.

<!DOCTYPE HTML>
<html>
<head>
    <title>Getting Started: Serving MVC Project Structure</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p>Welcome to the Spring MVC project</p>
</body>
</html>

 

3.1 Thymeleaf

Thymeleaf is modern server-side Java template engine that emphasizes natural HTML templates. For more details, refer to our existing article

 

4. Spring MVC and Spring Boot

If you are starting your project, Spring Boot should be your default choice to build Spring MVC application. Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications you can “just” run.

 

4.1 Spring Boot Starters

When we start with the Spring Boot, one of the fundamental questions which come to our mind is why do we need Spring Boot Starters? or how these starters will help me in my application?

With Spring Boot Starters, bootstrapping our Spring-MVC web application is straightforward, We need to include spring-boot-starter-web starter in our pom.xml.

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Note: For more details on starters, refer to our existing article on Spring Boot Starters.

Please read following articles for building Spring MVC web application using Spring Boot.

 

5. Spring MVC Controller

The Spring MVC controller handles HTTP request in Spring MVC application. Use the @Controller annotation to mark a controller.

@Controller
@RequestMapping("/greeting")
public class GreetingController {

    @GetMapping
    public String greeting(final Model model){
        model.addAttribute("message", "Welcome to our sample controller");
        return "greeting";
    }
}

Let’s try to understand different features of our MVC Controller.

  • @Controller annotation registers our class as Controller with Spring.
  • @RequestMapping("/greeting") will ensure that our class will process any request mapped to /greeting URI.
  • Our greeting method is annotated with @GetMapping which means it will call this method when a GET request will be sent to /greeting URI.
  • Once greeting method is called, it is saving a message in the Model class and returning a view (in our example view name is “greeting”).
  • In our viewResolver, we configured following properties
    • prefix = <em>/WEB-INF/view/</em>
    • suffix = <em>.jsp</em>
  • ViewResolver will try to resolve view information sent from our controller by combining prefix and suffix configured in our application.
  • Final information about the view will be /WEB-INF/view/greeting.jsp. Spring will try to find greeting.jsp in the /WEB-INF/view/ which will be used to display output on the front end.

 

Summary

In this Spring MVC tutorial, We created a simple web application using traditional XML based configuration and using Java configuration. In the last part of this post, we learned how to create a Spring MVC project using Spring Boot.

Comments are closed.