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


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 😀

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.

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.

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.


  • Article By: Varun Shrivastava

  • Varun Shrivastava is an innovative full stack web developer. He is a passionate blogger and loves to write about philosophy, programming, tech and relationships. He works as a Software Developer. This is his den, you can get in touch with him here anytime you want.
  • Website Search
  • Free Ebook Download ($7.06 Value)



  • Grab the Deal Now!

    Hostgator  Starting @$3.95/mo

  • DigitalOcean Free Credits!