• Skip to main content
  • Skip to primary sidebar
BMA

BeMyAficionado

Inspire Affection

Spring MVC – Build Project In Java With Gradle From Scratch (No XML)

August 18, 2019 by varunshrivastava 1 Comment

Hi folks, after a long time I revisited Spring MVC because of some project requirement and in the next moment, I was dealing with all sorts of configurations. If you have worked on Spring MVC before (not SpringBoot), you will know what am I referring to. All sorts of XML files (web.xml and spring-context etc).

And to be clear I hate all that clutter. So, instead of dealing with XMLs, I did it in Java. The package manager I used was Gradle (pretty clear from the heading too (:p)). Okay, so the scope of this article is just to build a project from scratch using Spring MVC dependencies. So do not expect anything more 😀

Table of Contents

  • Install Gradle
  • Setting Up Folder Structure
  • Make It Java Project
  • Add Spring Dependencies
  • Configure Spring MVC
    • Packages and Classes
    • Create View Inside Webapp Folder
  • Deploy In Tomcat Server
  • Conclusion

Install Gradle

This is the first step of the requirement. If you are a Java developer then chances are you already have it in your machine. But if you are new then don’t worry just fire below commands in order and you will be good to go.

There are different ways to install gradle. But the developer way to install any required piece of tool or software is by using the Software Development Kit Manager. I mostly prefer Homebrew and Sdkman for managing the development kit.

If you are working on Mac then it is fairly easy to install. And if you are on windows then you will have to do a little bit more. I will leave the installation to you. You are smart enough to choose the package manager for yourself.

So, with Sdkman, fire below commands to install gradle on your system.

sdk install gradle 5.6

Once it is downloaded and installed type below command.

sdk use gradle 5.6

And just to make sure everything is working fine:

gradle --version

You will see below information depending on your machine state:

Gradle Version Terminal Command
gradle --version

Cool. Let’s setup Spring MVC now.

  • A Brief Introduction About Gradle

Setting Up Folder Structure

I can very easily do it using some IDE such as Intellij but then you would miss the crux of it all. So, I want to do everything manually and take you through each and every step. Starting from creating the folder structure for your application.

So, to create the folder structure first create a new folder that will be the container for your application (same as project name in your IDE).

mkdir SpringMvcBoilerplate
cd SpringMvcBoilerplate

Yo. Now you have your project container ready. Let’s create the folder structure for our Java application.

mkdir -p src/main/java

Usually, you will also create a folder structure for the test cases but since you won’t be writing any test cases in this project so it is not relevant. So skipping it.

So yeah, you have created the folder structure of your Java application.

  • Shopping Cart Application In Java (Object Oriented)
  • How To Start Thinking In Object-Oriented Way

Make It Java Project

So far that was just empty folders you have there. It is time to convert it into an actual Java project. And after that, you will add Spring Dependency to convert it into a Spring MVC project.

Let’s create build.gradle file and add below line of code into it.

cat > build.gradle
apply plugin: 'java'

Press ^d to end file.

This single line brings a significant power to you. Just type gradle tasks and see all the available tasks you can perform with it.

gradle tasks

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.
war - Generates a war archive with all the compiled classes, the web-app content and the libraries.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'JavaVersionCheck'.
components - Displays the components produced by root project 'JavaVersionCheck'. [incubating]
dependencies - Displays all dependencies declared in root project 'JavaVersionCheck'.
dependencyInsight - Displays the insight into a specific dependency in root project 'JavaVersionCheck'.
dependentComponents - Displays the dependent components of components in root project 'JavaVersionCheck'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'JavaVersionCheck'. [incubating]
projects - Displays the sub-projects of root project 'JavaVersionCheck'.
properties - Displays the properties of root project 'JavaVersionCheck'.
tasks - Displays the tasks runnable from root project 'JavaVersionCheck'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 618ms

You can build artifacts, generate java docs and much-much more. All this happened just by adding a single line of code in your build.gradle file.

Now go ahead and build your project.

gradle clean build

After firing the command you will see that a build directory has been created inside your project.

SpringMvcBoilerplate
|_ src
  |_ main
    |_ java
  build.gradle
  build
    |_ classes
    |_ libs
    |_ tmp
    |_ generated
  • classes: The project’s compiled .class files.
  • libs: Assembled project libraries (usually JAR and/or WAR files).

You must be wondering there is not classes folder. Well, that is because you do not have any Java file in your project. So, far you have a fully working Java project.

Let’s open the project in IDE now. Please choose Idea Intellij (:D). You will see that it opens perfectly with your IDE and src/main/java folders has been added to the working directory by Intellij.

Open Project In Intellij First View
Open Project In IDE

Add Spring Dependencies

So far so good. Let’s add Spring MVC dependencies to our project. Copy and paste the below code in your build.gradle file.

apply plugin: 'java'
apply plugin: 'war'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.springframework:spring-webmvc:4.2.4.RELEASE'
    providedCompile 'javax:javaee-web-api:7.0'
}

war {
    archiveBaseName = 'helloworld'
    archiveVersion = '0.1.0'
}

After pasting the code in your build.gradle, click on the Import Changes project showed in the bottom right.

All the required spring dependencies will be downloaded and added to the classpath by gradle. In the background, Intellij runs the same command i.e. gradle clean build.

Configure Spring MVC

This used to be the hard part for me. Creating all the XML files and copy-pasting the boilerplate tags at the start and then bootstrapping everything else to make it work.

But after Spring MVC 3, you no longer have to use XML to make it work. You can configure your entire application from the code itself. The biggest advantage – No need to copy-paste or maintain the nasty XML files. Don’t get me wrong, I love XML but not for configuring my application.

Okay so let’s start…

Packages and Classes

There is a total of three configuration classes that are required to bootstrap the entire application.

  • RootConfig.java: This class will be used to create the root application context by Spring MVC.
  • WebConfig.java: This class will be used to create a servlet application context.
  • WebInit.java: This class will initialize the entire application.

Here is my package structure for this project.

Packages and Classes for the project
Packages and Classes

RootConfig.java

Now, first of all, you need to declare your root config class for the application.

Since I’m not going to provide any explicit configuration, therefore, will just leave it empty.

package com.bma.app.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class RootConfig {
}

WebConfig.java

This class will be used to bootstrap the entire application. You will provide the base packages of your application to scan at the start. You will also tell the Spring MVC to Enable MVC support for the project by importing Spring MVC Configuration from WebMvcConfigurationSupport.

package com.bma.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.bma.app")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

Here, you have noticed that I have created a Bean of InternalResourceViewResolver. It is a way to tell Spring how to get the Servlet View based on the name. In this project, I’m using JSP as application view so I’ve mentioned the same.

WebInit.java

This class will provide the required configuration to the Spring.

package com.bma.app.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

@Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

Here, you will pass the RootConfig.class, WebConfig.class by overriding the respective method of the AbstractAnnotationConfigDispatcherServletInitializer.

Cool. You have made all the required configuration to start the application. Now, all you need is a controller and a view file. Then bundle it into a war and deploy it on a Tomcat Server.

HelloWorldController.java

package com.bma.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/")
public class HelloWorldController {

    @RequestMapping(value = "hello", method = RequestMethod.GET)
    public String helloWorld() {
        return "hello";
    }
}

Create View Inside Webapp Folder

Create a webapp folder inside src/main. So it should be src/main/webapp.

After that create a hello.jsp file inside the webapp folder.

hello.jsp

cat > src/main/webapp/hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
Hello World!
</body>
</html>

So everything is done.

Now, let’s build it using gradle by firing below command from the root of the project.

gradle clean build

You will find a war file with the same name that you mentioned in the build.gradle file.

ls build/libs/
helloworld-0.1.0.war

Deploy In Tomcat Server

I hope you are using Intellij because then you can simply follow along the lines.

So to deploy our app in the tomcat server.

Click on Run > Run…

Run Application with Configuration
Run Application

Click Edit Configurations…

Edit Configurations in Intellij
Edit Configurations

Select Local Tomcat Server

Local Tomcat Server Intellij
Local Tomcat Server

Do the following:

  • Provide a name: SpringMvcBoilerplate
  • Select Application Server: Tomcat 9.0.22
  • Configure URL: http://localhost:9090/
Tomcat Server Configuration
Tomcat Server Configuration

Click on the Fix button in the bottom right

Fix Button
Fix Button

Select helloworld-0.1.0.war (exploded)

Fix Button Confugrations
Fix Configurations
  • Set the Application Context Path
  • Click Apply
  • Click Run
Application Configurations
Application Configuration

The tomcat server will start and deploy the application to it.

Tomcat Server Logs
Tomcat Logs

Your browser will automatically open you should see Hello World!

I hope everything worked for you as it worked for me. In case you encountered any error related to the server, code etc… then don’t spend too much time troubleshooting. Simply shoot a comment below and I will help you asap.

I presume if you encounter any error then it might be because of the Tomcat server and deployment. It tends to get tricky sometimes.

Conclusion

So far you have created a Java project, added Spring MVC dependencies and configured entire application without creating an XML file.

I hope you liked the article and if YES then do share it with other budding developers in your circle.

Related

Filed Under: Programming Tagged With: configuration, Gradle, java, no xml, spring-mvc

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