Spring WebApplicationInitializer with Example
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 > <!-- Provide a Servlet Name --> < servlet-name >myDispatcherServlet</ servlet-name > <!-- Provide a fully qualified path to the DispatcherServelt class --> < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class > < load-on-startup >1</ load-on-startup > </ servlet > < servlet-mapping > <!-- Provide a Servlet Name that you want to map --> < servlet-name >myDispatcherServlet</ servlet-name > <!-- Provide a url pattern --> < 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
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3wiki.net/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > < modelVersion >4.0.0</ modelVersion > < groupId >com.w3wiki</ groupId > < artifactId >spring-calculator</ artifactId > < packaging >war</ packaging > < version >0.0.1-SNAPSHOT</ version > < name >spring-calculator Maven Webapp</ name > < url >http://maven.apache.org</ url > < dependencies > < dependency > < groupId >junit</ groupId > < artifactId >junit</ artifactId > < version >3.8.1</ version > < scope >test</ scope > </ dependency > <!-- 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 > </ 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.w3wiki.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 xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3wiki.net/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> </ 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
// Java Program to Demonstrate Calculator Application // Initializer Class package com.w3wiki.calculator.config; // Importing required classes 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; // Class // Implementing WebApplicationInitializer interface public class CalculatorApplicationInitializer implements WebApplicationInitializer { // Method public void onStartup(ServletContext servletContext) throws ServletException { 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 (Custom URL) 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.w3wiki.calculator.controllers’ package.
File: GfgController.java
Java
// Java Program to Illustrate GfgController Class package com.w3wiki.calculator.controllers; // Importing required classes import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; // Class @Controller public class GfgController { @RequestMapping ( "/welcome" ) @ResponseBody // Testor Method public String helloGfg() { return "Welcome to w3wiki!" ; } } |
Before running the application add the below lines to the application-config.xml file.
<context:component-scan base-package="com.w3wiki.calculator.controllers"></context:component-scan>
File: Updated application-config.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3wiki.net/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> < context:component-scan base-package = "com.w3wiki.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
Contact Us