• Skip to main content
  • Skip to primary sidebar
BMA

BeMyAficionado

Inspire Affection

Spring Web MVC (3.x) Configuration From Scratch (Using XML)

November 8, 2019 by varunshrivastava Leave a Comment

It feels like travelling back in time like 6-7 years when we had to configure the Spring Web MVC using XML.

It was so dreadful for me back then.

It is dreadful for me now as well.

I know many of you might be struggling to set up the Spring Web MVC older versions (versions from 3.x) and so on.

I know this because I’m struggling with it myself. Mostly because I’m working on a legacy system powered by Spring Web MVC 3.x that needs to be migrated to cloud.

And this article is really good for starters as well.

If you are starting out with web development then this is a good starting point as you will know about the working principles behind Spring Web MVC.

And if you are someone just looking for a quick boilerplate that you can use to work on, then grab it from here: Spring Web MVC Boilerplate.

Okay… so let’s begin.

Table of Contents

  • Start With The Directory Structure
  • Setting Up Spring Web MVC Required Dependencies
  • Setting Up web.xml
  • Setting Up dispatcher-servlet.xml File
  • Create HelloWorldController
  • Deploy The War On Tomcat Container

Start With The Directory Structure

The directory structure is very important if you are going to set up the Spring Web MVC in the fastest/easiest way possible. The directory structure is used by default to package your artefact.

So if you do not have the right directory structure than you might miss to include the necessary files and folder in your generated WAR file that will later cause a problem (after deployment) and takes a lot more time to resolve than usual.

Try to start with the right directory structure.

Default Directory Structure for Spring Web MVC
Default Directory Structure for Spring Web MVC

Copy-paste below command to create all the required directories.

mkdir -p src/main/webapp/WEB-INF
mkdir -p src/main/java
mkdir -p src/main/resources
mkdir -p src/test/java
mkdir -p src/test/resources

Note: resources folder is not required but it’s good to have

So, once you are done with the directory structure, let’s start by setting up the required dependencies for Spring Web MVC application.

Setting Up Spring Web MVC Required Dependencies

I use gradle for packaging and building Java applications. And you should too. Gradle is very easy and modern with a very crisp syntax.

I have written and explained it here:

  • Brief Introduction Of Gradle
  • Spring Web MVC – Build Project In Java With Gradle (no XML)

Coming back to setting up required dependencies in your project.

Create build.gradle file at the root of your project. For example if your project folder name is SpringWebMvc then create a file directly inside your project folder as build.gradle.

Prerequisite: Install and setup gradle on your machine.

Tip: Install Gradle using Brew. Code: brew install gradle.
Read How to Setup Homebrew.

In build.gradle add all the required dependencies. Simply copy and paste below code:

cat > build.gradle
plugins {
    id "java"
    id "war"
}

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.springframework', name: 'spring-context', version: '3.1.0.RELEASE'
    compile group: 'org.springframework', name: 'spring-webmvc', version: '3.1.0.RELEASE'
    compile group: 'org.springframework', name: 'spring-web', version: '3.1.0.RELEASE'

    providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'

    compile group: 'commons-logging', name: 'commons-logging', version: '1.2'
    compile group: 'log4j', name: 'log4j', version: '1.2.14'

}

Great. So far so good.

Now just for a sanity check try to run following command: gradle clean build.

If the command is successful, it will show build successful.

gradle clean build
gradle clean build

And you will see a newly generated folder with the name build.

It means everything is good and we can move forward to setting up web.xml and dispatcher-servlet.xml.

Setting Up web.xml

First of of all, if you are new to the web development world then I would recommend you to read about Servlet containers like Tomcat and see how they make use of web.xml to identify which classes to load, what parameters to set in the context, and how to intercept requests coming from browsers.

In short, web.xml is used by Tomcat (or servlet containers) and it is called Deployment Descriptor. It tells tomcat which classes to load and how to intercept the incoming URLs for the application.

So, in Spring Web MVC, we have only one Servlet called DispatcherServlet. This DispatcherServlet extends from HttpServlet class (part of servlet-api).

You can think of DispatcherServlet as a controller that maps every incoming request to its correct Controller.

Baeldung has explained it rather beautifully here.

So with that information in mind, let’s configure the web.xml file in such a way that it will forward every request to the DispatcherServlet class of Spring MVC.

cat > src/main/webapp/WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    <display-name>Demo for understanding web.xml of spring mvc project</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <!-- ===================================================== -->
    <!--  1. Create root context with spring listener          -->
    <!--     Remove this means only use servlet contxt         -->
    <!-- ===================================================== -->
<!--    <listener>-->
<!--        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
<!--    </listener>-->

    <!-- ===================================================== -->
    <!-- Can modify default root context config file           -->
    <!-- ===================================================== -->
    <!--
    <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>
     -->


    <!-- ===================================================== -->
    <!--  2. Define servlet with private context               -->
    <!-- ===================================================== -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- ================================================= -->
        <!-- Set contextConfigLocation to empty                -->
        <!-- means only use root context                       -->
        <!-- ================================================= -->
        <!--
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value></param-value>
        </init-param>
         -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- ===================================================== -->
    <!-- One servlet, the dispatcher, to rule it all           -->
    <!-- ===================================================== -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

</web-app>

Here, we have defined servlet as org.springframework.web.servlet.DispatcherServlet with its mapping.

Also, one important thing here is the name of the servlet i.e dispatcher.

This name is used to create the dispatcher-servlet.xml file. So, whatever name you mention in the web.xml servlet tag, the same name should be used to create the file as {servlet_name}-servlet.xml.

Setting Up dispatcher-servlet.xml File

Now that you have set up the web.xml file successfully, it is time to set up the dispatcher-servlet.xml.

Simply, copy and paste the below code:

cat > src/main/webapp/WEB-INF/dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <mvc:annotation-driven />
    <!-- register controller in servlet private context -->
    <context:component-scan base-package="com.spring.sample.controller"/>
    <mvc:default-servlet-handler />

</beans>

Here we are telling the Dispatcher servlet that we are using Annotation in our application. And also the path where it needs to scan for all the spring components.

This is pretty straight-forward once you read about the DispatcherServlet in detail.

Let’s create our HelloWorldController.

Create HelloWorldController

Okay, so we have everything in place. Let’s create our HelloWorldController.

cat > src/main/java/com/spring/sample/controller/HelloWorldController.java
package com.spring.sample.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorldController {

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    @ResponseBody
    public String helloWorld() {
        return "Hello World!";
    }
}

Superb.

Now, let’s build the application and look inside the hood.

To build the application, run the following command: gradle clean build.

You should see the war artefact inside build/libs/SpringMVCSample.war.

Unzip the file and look for its content. To unzip the war file, run the following command:

unzip -d temp build/libs/SpringMVCSample.war

Then use tree command to see the structure.

You should see the following content inside:

Deployable WAR Contents
Deployable WAR Contents

Make sure you have a similar structure with all the required files in place. This is the minimum configuration that is required to run the Spring Web MVC application on the Tomcat server.

Deploy The War On Tomcat Container

I’m running out of time, so I leave the Tomcat setup up to you. All you need to do is place the war file inside the webapps directory of tomcat.

Tomcat will then deploy the artefact which you can access via browser.

This is what you will see on a successful deployment.

Hello World means it is working
Hello World

Let me know if you need any information related to any of the stuff discussed in this article. The best and fastest way to get the answer is via comments.

Related

Filed Under: Programming Tagged With: 3.x, spring web mvc, spring-mvc, web.xml, xml

Primary Sidebar

Subscribe to Blog via Email

Do you enjoy the content? Feel free to leave your email with me to receive new content straight to your inbox. I'm an engineer, you can trust me :)

Join 874 other subscribers

Latest Podcasts

Recent Posts

  • Is The Cosmos a Vast Computation?
  • Building Semantic Search for E-commerce Using Product Embeddings and OpenSearch
  • Leader Election with ZooKeeper: Simplifying Distributed Systems Management
  • AWS Serverless Event Driven Data Ingestion from Multiple and Diverse Sources
  • A Step-by-Step Guide to Deploy a Static Website with CloudFront and S3 Using CDK Behind A Custom Domain

Recent Comments

  • Varun Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Vaibhav Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Varun Shrivastava on Should Girls Wear Short Clothes?
  • D on Should Girls Wear Short Clothes?
  • disqus_X5PikVsRAg on Basic Calculator Leetcode Problem Using Object-Oriented Programming In Java

Categories

  • Blogging
  • Cooking
  • Fashion
  • Finance & Money
  • Programming
  • Reviews
  • Software Quality Assurance
  • Technology
  • Travelling
  • Tutorials
  • Web Hosting
  • Wordpress N SEO

Archives

  • November 2024
  • September 2024
  • July 2024
  • April 2024
  • February 2024
  • November 2023
  • June 2023
  • May 2023
  • April 2023
  • August 2022
  • May 2022
  • April 2022
  • February 2022
  • January 2022
  • November 2021
  • September 2021
  • August 2021
  • June 2021
  • May 2021
  • April 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • February 2020
  • December 2019
  • November 2019
  • October 2019
  • August 2019
  • July 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
  • January 2019
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016

Tags

Affordable Hosting (4) algorithms (4) amazon (3) aoc-2020 (7) believe in yourself (4) best (4) database (4) earn money blogging (5) education (4) elementary sorting algorithms (4) experience (3) fashion (4) finance (6) Financial Freedom (7) food (7) friends (3) goals (5) google (5) india (10) indian cuisine (5) indian education system (4) java (16) life (16) life changing (4) love (4) make money (3) microservices (9) motivation (4) oops (4) podcast (6) poor education system (4) principles of microservices (5) problem-solving (7) programmer (5) programming (28) python (5) reality (3) seo (6) spring (3) success (10) success factor (4) technology (4) top 5 (7) typescript (3) wordpress (7)

Copyright © 2025 · Be My Aficionado · WordPress · Log in

Go to mobile version