Skip to content

Spring MVC Java Configuration#

Spring MVC Java Configuration Process#

  • When we create an new Spring MVC project. There are some steps that we need to setup as below.
    • Add Spring MVC configuration class.
      • Add support for Spring component scanning.
      • Add support for conversion, formatting and validation.
      • Configure Spring MVC View Resolver.
    • Add Java configuration class for configuring Dispatcher Servlet.
      • Configure Spring MVC Dispatcher Servlet.
      • Set up URL mappings to Spring MVC Dispatcher Servlet.

Add Spring MVC Configuration Class#

  • We will create a class called SpringApplicationConfig, where we will register all Spring-related beans using Spring's Java-based configuration style. Let's see the code below.
SpringApplicationConfig.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package spring.mvc.java.based.configuration.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.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan({"spring.mvc.java.based.configuration"})
public class SpringApplicationConfig {

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

}
  • As you can see, in this class, we will use annotation @ComponentScanand the input class path for packages that we want Spring Framework to scan. This annotation is like we are using tag <context:component-scan base-package="....." /> in Spring MVC XML Configuration.
  • Next, we also need to use annotation @EnableWebMvc to Enable Spring MVC-specific annotations. This annotation is like we are using tag <mvc:annotation-driven/> in Spring MVC XML Configuration.
  • Finally, we will create a viewResolver bean which will be used for Spring MVC View Resolver.
    • In which, we will create a new instance of InternalResourceViewResolver then we will configure viewClass to set the view class to be used by the view resolver to JstlView, which is a Spring view class that provides support for JSTL (JavaServer Pages Standard Tag Library).
    • The prefix is set to "/WEB-INF/views/" and the suffix to ".jsp", which means that when a view name is returned by a controller method, Spring will look for a JSP file with that name in the "/WEB-INF/views/" directory with a ".jsp" extension.

Add Java Configuration Class For Configuring Dispatcher Servlet#

  • Let's create a Java class that implements the WebApplicationInitializer interface as below which is used to configure a web application in a Servlet 3.0+ container. This class will replace our traditional web.xml.
WebInitializer.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package spring.mvc.java.based.configuration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import spring.mvc.java.based.configuration.config.SpringApplicationConfig;

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

public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringApplicationConfig.class);
        context.setServletContext(servletContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

}
  • As you can see we will override the method onStartup, this method is called by the container when the application starts up.
  • Then we will create a new AnnotationConfigWebApplicationContext for creating and configuring Spring web application Context using Java-based configuration as in the image below.

 #zoom

  • Next, the application context is then set to the servlet context using the setServletContext() method.
  • Then we will create a new DispatcherServlet with the application context as a param.
  • Then we will create an instance of ServletRegistration.Dynamic by using servletContext.addServlet() and the DispatcherServlet will be added into a dynamic servlet registration with the name is dispatcher and it maps to the root URL (/).
  • Finally, the servlet's loadOnStartup property is set to 1, indicating that the servlet should be loaded on application startup.

Example With Spring MVC Java-Based Configuration#

  • So let's take the example for Spring MVC Java-Based configuration. Let's create a maven project and follow steps below.

Dependencies#

  • Let's create the pom.xml with the content as below.
pom.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>com.spring.core</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <artifactId>spring-mvc-xml-configuration</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.24</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
  • Firstly, we would like to package our project to .war file by using tag packaging instead of .jar (default) because we will use this .war file to deploy to Tomcat Server.
  • Next, we will use the dependency spring-webmvc to use Spring MVC framework.
  • Finally, we will use the plugin below, for supporting building .war file, we also have to configure path to the file web.xml that we are going to create in the next steps. With this plugin, our .war file will be packaged will all references and supported libraries, classes and configuration files.
1
2
3
4
5
6
7
<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
                <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
        </configuration>
</plugin>

Add Spring MVC Configuration Class#

  • We will create a class called SpringApplicationConfig, where we will register all Spring-related beans using Spring's Java-based configuration style. Let's see the code below.
SpringApplicationConfig.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package spring.mvc.java.based.configuration.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.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan({"spring.mvc.java.based.configuration"})
public class SpringApplicationConfig {

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

}
  • We will use annotation @ComponentScanand the input class path for packages that we want Spring Framework to scan. Then, we also need to use annotation @EnableWebMvc to Enable Spring MVC-specific annotations.
  • Finally, we will create a viewResolver bean which will be used for Spring MVC View Resolver.

Add Java Configuration Class For Configuring Dispatcher Servlet#

  • Let's create a Java class that implements the WebApplicationInitializer interface as below which is used to configure a web application in a Servlet 3.0+ container. This class will replace our traditional web.xml.
WebInitializer.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package spring.mvc.java.based.configuration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import spring.mvc.java.based.configuration.config.SpringApplicationConfig;

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

public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringApplicationConfig.class);
        context.setServletContext(servletContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }

}

Create Views#

  • So, let's create the folder views inside the WEB-INF as below.

 #zoom

Then inside the views we will create an example welcome.jsp with the content as below.

welcome.jsp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>First JSP</title>
</head>
<body>
<h3>Welcome ${name}</h3><br>
</body>
</html>
  • In this welcome.jsp file, we just simply map the value of variable name that we will define in the Controller.

Create Controller#

  • Next, let's create a controller class in side the parent package spring.mvc.java.based.configuration.controller that we configured in the SpringApplicationConfig.java class.

  • The created controller WelcomeController will have the content as below.

WelcomeController.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package spring.mvc.java.based.configuration.controller;  

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

@Controller  
public class WelcomeController {  

    @RequestMapping("/welcome")  
    public String welcome(ModelMap modelMap) {  
        modelMap.addAttribute("name", "Duc");  
        return "welcome";  
    }  

}
  • We can annotate classic controllers with the @Controller annotation. This is simply a specialization of the @Component class, which allows us to auto-detect implementation classes through the classpath scanning.
  • We typically use @Controller in combination with a @RequestMapping annotation for request handling methods.
  • In the api /welcome, we just simply add an attribute name with value Duc to the welcome.jsp view, the return "welcome"; means we will use the file welcome.jsp in the views folder that we configured and the attribute name will be mapped with value Duc there.

Building War File#

  • Now, let's run the command mvn clean package to package the .war file as below.

 #zoom

  • So, in the .war file we can see, we already have all classes, libraries and configuration files.

Testing#

  • Finally, let's deploy this .war file into the Tomcat server and then go to the browser and put the url http://localhost:8080/spring-mvc-xml-configuration/welcome to check the successful result.

 #zoom

See Also#

References#