In Spring, WebApplicationInitializer is an Interface and it is Servlet 3.0+ implementation to configure ServletContext programmatically in comparison to the traditional way to do this using the web.xml file. This interface is used for booting Spring web applications. WebApplicationInitializer registers a Spring DispatcherServlet and creates a Spring web application context. Traditionally, Java Web Applications based on Servlets were using the web.xml file to configure a Java Web Application. Since Servlet 3.0, web applications can be created programmatically via Servlet context listeners.
Approach: Traditional XML-based
In the traditional approach, the spring developers building a web application will need to register Spring’s DispatcherServlet. For example, we can take WEB-INF/web.xml, this would typically be done as follows:
XML
< servlet >
< servlet-name >myDispatcherServlet</ servlet-name >
< servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >
< load-on-startup >1</ load-on-startup >
</ servlet >
< servlet-mapping >
< servlet-name >myDispatcherServlet</ servlet-name >
< url-pattern >/gfg.com/*</ url-pattern >
</ servlet-mapping >
|
Approach: Code-based with WebApplicationInitializer
Below is the equivalent DispatcherServlet registration logic, WebApplicationInitializer-style:
public class CalculatorApplicationInitializer
implements WebApplicationInitializer {
// Method
public void onStartup(ServletContext servletContext)
throws ServletException
{
// Creating objects of XmlWebApplicationContext
// class
XmlWebApplicationContext webApplicationContext
= new XmlWebApplicationContext();
webApplicationContext.setConfigLocation(
"classpath:application-config.xml");
// Creating a dispatcher servlet object
DispatcherServlet dispatcherServlet
= new DispatcherServlet(webApplicationContext);
// Registering Dispatcher Servlet with Servlet
// Context
ServletRegistration
.Dynamic myCustomDispatcherServlet
= servletContext.addServlet(
"myDispatcherServlet", dispatcherServlet);
// Setting load on startup
myCustomDispatcherServlet.setLoadOnStartup(1);
// Adding mapping url
myCustomDispatcherServlet.addMapping("/gfg.com/*");
}
}
So now let’s develop a sample complete project and see how WebApplicationInitializer helps us to build a spring web application using java based configuration.
Implementation: Project Demonstrating Spring WebApplicationInitializer
Step 1: Set up the project
Note: We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS on your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
Go to your STS IDE then create a new maven project, File > New > Maven Project, and choose the following archetype as shown in the below image as follows:
Step 2: Adding Some Maven Dependencies
Add the following Maven dependencies and plugin to the pom.xml file.
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- plugin -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
Below is the complete code for the pom.xml file after adding these dependencies.
File: pom.xml
XML
< modelVersion >4.0.0</ modelVersion >
< groupId >com.geeksforgeeks</ groupId >
< artifactId >spring-calculator</ artifactId >
< packaging >war</ packaging >
< version >0.0.1-SNAPSHOT</ version >
< name >spring-calculator Maven Webapp</ name >
< dependencies >
< dependency >
< groupId >junit</ groupId >
< artifactId >junit</ artifactId >
< version >3.8.1</ version >
< scope >test</ scope >
</ dependency >
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-webmvc</ artifactId >
< version >5.3.18</ version >
</ dependency >
< dependency >
< groupId >javax.servlet</ groupId >
< artifactId >javax.servlet-api</ artifactId >
< version >4.0.1</ version >
< scope >provided</ scope >
</ dependency >
</ dependencies >
< build >
< finalName >spring-calculator</ finalName >
< plugins >
< plugin >
< groupId >org.apache.maven.plugins</ groupId >
< artifactId >maven-war-plugin</ artifactId >
< version >2.6</ version >
< configuration >
< failOnMissingWebXml >false</ failOnMissingWebXml >
</ configuration >
</ plugin >
</ plugins >
</ build >
</ project >
|
Step 3: Code-based Approach with WebApplicationInitializer
Before moving into the coding part let’s have a look at the file structure in the below image.
So at first create an src/main/java folder and inside this folder create a class named CalculatorApplicationInitializer and put it inside the com.geeksforgeeks.calculator.config package and implement the WebApplicationInitializer interface. Refer to the below image.
Now in this class, we have to perform the following 2 major operations as listed below as follows:
- Create a dispatcher servlet object
- Register Dispatcher Servlet with Servlet Context
And we can do it by writing these lines of code
Operation 1: Create a dispatcher servlet object:
XmlWebApplicationContext webApplicationContext = new XmlWebApplicationContext();
// Create a dispatcher servlet object
DispatcherServlet dispatcherServlet = new DispatcherServlet(webApplicationContext);
Operation 2: Register Dispatcher Servlet with Servlet Context
ServletRegistration.Dynamic myCustomDispatcherServlet = servletContext.addServlet("myDispatcherServlet",
dispatcherServlet);
- Go to the src/main/resources and create an XML file.
- Name the file as application-config and paste the below code inside this file.
File: application-config.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?>
</ beans >
|
And below is the complete code for the CalculatorApplicationInitializer.java file. This is the class where we have followed the Code-based Approach with WebApplicationInitializer.
File: CalculatorApplicationInitializer.java
Java
package com.geeksforgeeks.calculator.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class CalculatorApplicationInitializer
implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException
{
XmlWebApplicationContext webApplicationContext
= new XmlWebApplicationContext();
webApplicationContext.setConfigLocation(
"classpath:application-config.xml" );
DispatcherServlet dispatcherServlet
= new DispatcherServlet(webApplicationContext);
ServletRegistration
.Dynamic myCustomDispatcherServlet
= servletContext.addServlet(
"myDispatcherServlet" , dispatcherServlet);
myCustomDispatcherServlet.setLoadOnStartup( 1 );
myCustomDispatcherServlet.addMapping( "/gfg.com/*" );
}
}
|
Step 4: Create Controller and Test The Application
Go to the src/main/java folder and inside this folder create a class named GfgController and put it inside the /com.geeksforgeeks.calculator.controllers’ package.
File: GfgController.java
Java
package com.geeksforgeeks.calculator.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GfgController {
@RequestMapping ( "/welcome" )
@ResponseBody
public String helloGfg()
{
return "Welcome to GeeksforGeeks!" ;
}
}
|
Before running the application add the below lines to the application-config.xml file.
<context:component-scan base-package="com.geeksforgeeks.calculator.controllers"></context:component-scan>
File: Updated application-config.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?>
< context:component-scan base-package = "com.geeksforgeeks.calculator.controllers" ></ context:component-scan >
</ beans >
|
Step 5: Run The Application
Lastly, run your spring MVC application and hit the following URL
http://localhost:8080/spring-calculator/gfg.com/welcome
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
03 May, 2022
Like Article
Save Article