Skip to content

Spring MVC XML Configuration#

Spring MVC XML Configuration Process#

  • When we create an new Spring MVC project. There are some steps that we need to setup as below.
    • Add configurations to file WEB-INF/web.xml.
      • Configure Spring MVC Dispatcher Servlet.
      • Set up URL mappings to Spring MVC Dispatcher Servlet.
    • Add configurations to file: WEB-INF/spring-mvc-servlet.xml
      • Add support for Spring component scanning.
      • Add support for conversion, formatting and validation.
      • Configure Spring MVC View Resolver.

Configure Spring DispacherServlet#

  • If you haven't what is the DispacherServlet. You can view more here
  • So to configure the DispatcherServlet, firstly, we have to create a folder WEB-INF which is located in the folder src/main/webapp/. Then in the src/main/webapp/WEB-INF/ folder we will create the web.xml configuration file as below.
web.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
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

    <display-name>spring-mvc-xml-configuration</display-name>

<!--    Spring MVC Configs-->

<!--    Step 1: Configure Spring MVC Dispatcher Servlet-->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-xml-configuration-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

</web-app>
  • The WEB-INF directory contains the deployment descriptors for the Web application (web.xml and weblogic.xml) and two subdirectories for storing compiled Java classes and library JAR files. These subdirectories are respectively named classes and lib
  • So in the web.xml we will configure a servlet which will use the class DispatcherServlet with a parameter is contextConfigLocation and the value is the path to a configuration file also in the WEB-INF folder, but this file will contain all of our Spring Web MVC-specific components (beans).
  • Then we configure the load-on-startup with value is 1. The load-on-startup element of web-app loads the servlet at the time of deployment or server start if value is positive. It is also known as pre initialization of servlet.
  • We can pass positive and negative value for the servlet.
    • If we pass the positive value, the lower integer value servlet will be loaded before the higher integer value servlet. In other words, container loads the servlets in ascending integer value. The 0 value will be loaded first then 1, 2, 3 and so on.
    • If we pass the negative value, servlet will be loaded at request time, at first request.

Set up URL mappings to Spring MVC Dispatcher Servlet#

  • Now, in the web.xml we will continue to set up URL mappings to Spring MVC Dispatcher Servlet as below.
web.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
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

    <display-name>spring-mvc-xml-configuration</display-name>

<!--    Spring MVC Configs-->

<!--    Step 1: Configure Spring MVC Dispatcher Servlet-->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-xml-configuration-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

<!--    Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet-->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
  • So we will use tag <servlet-mapping> to map the dispatcher servlet to the url /. It means we will catch all requests from the client and bind them to the dispatcher servlet and when the dispatcher servlet is creating, it will load an init param which has name contextConfigLocation and the value of it this the path to another config file spring-mvc-xml-configuration-servlet.xml.

Add Support For Spring Component Scanning#

  • Now, let's create the configuration file spring-mvc-xml-configuration-servlet.xml in the src/main/webapp/WEB-INF/ with the configuration for supporting Spring Component Scanning as below.
spring-mvc-xml-configuration-servlet.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- Step 3: Add support for component scanning -->
    <context:component-scan base-package="com.spring.core.spring.mvc.xml.configuration" />

</beans>
  • As you can see, we will use the tag context:component-scan and property base-package with the value is the package that we want Spring Framework to scan.

Add Support For Conversion, Formatting and Validation.#

  • Next, we will continue to add the configuration for supporting Conversion, Formatting and Validation into the spring-mvc-xml-configuration-servlet.xml as below.
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- Step 3: Add support for component scanning -->
    <context:component-scan base-package="com.spring.core.spring.mvc.xml.configuration" />

    <!-- Step 4: Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

</beans>
  • We will use the tag  <mvc:annotation-driven> to enable MVC configuration, so it means that we will registers a number of Spring MVC infrastructure beans and adapts to dependencies available on the classpath (for example, payload converters for JSON, XML, and others).

Configure Spring MVC View Resolver#

  • Finally, let's add the configuration for configuring the Spring MVC View Resolver as below.
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- Step 3: Add support for component scanning -->
    <context:component-scan base-package="com.spring.core.spring.mvc.xml.configuration" />

    <!-- Step 4: Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Step 5: Define Spring MVC view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view"/>
        <property name="suffix" value=".jsp"/>
     </bean>

</beans>
  • We will create a bean internalResourceViewResolver from the using the class org.springframework.web.servlet.view.InternalResourceViewResolver with 2 properties prefix and suffix.
    • In which the prefix will contain the path to the folder that contains views (Ex: /WEB-INF/views).
    • The suffix has the value is the type of the file used for the view (Ex: .jsp).

Example With Spring MVC XML Configuration#

  • So let's take the example for Spring MVC XML 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>

Configure web.xml#

  • Now, let's create the WEB-INF folder with the structure src/main/webapp/WEB-INF that we configured in the pom.xml as below.

 #zoom

  • Then inside the WEB-INF we will create the web.xml file for configuring the DispacherServlet and set up URL mappings to Spring MVC Dispatcher Servlet as below.
web.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
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

    <display-name>spring-mvc-xml-configuration</display-name>

<!--    Spring MVC Configs-->

<!--    Step 1: Configure Spring MVC Dispatcher Servlet-->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-xml-configuration-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

<!--    Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet-->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
  • So we you can see, in the dispatcher servlet configuration we will load Spring MVC configuration file spring-mvc-xml-configuration-servlet.xml. So, let's create this file on the next step.

Configure spring-mvc-xml-configuration-servlet.xml#

  • Now, let's create the configuration file spring-mvc-xml-configuration-servlet.xml in the src/main/webapp/WEB-INF/ with the configurations for supporting Spring Component Scanning, Spring MVC configuration supports and Spring MVC view resolver as below.
spring-mvc-xml-configuration-servlet.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
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- Step 3: Add support for component scanning -->
    <context:component-scan base-package="com.spring.core.spring.mvc.xml.configuration" />

    <!-- Step 4: Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Step 5: Define Spring MVC view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
     </bean>


</beans>
  • As you can see, in the Define Spring MVC view resolver we configured to use .jsp file for view in the path /WEB-INF/views/. So let's create it in the next step.

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 com.spring.core.spring.mvc.xml.configuration that we configured in the spring-mvc-xml-configuration-servlet.xml file.

  • 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 com.spring.core.spring.mvc.xml.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#