Spring MVC and Java-Based Configuration
Skip web.xml and dive into Java-based configuration. Some Java and a POM are all you need to get your projects configured the way you want them.
Join the DZone community and get the full member experience.
Join For FreeIn this aicle, we will see how to configure a Spring MVC application without using a web.xml. We will use Java-based configuration.
For this example, we will use a simple Maven web project.
Step 1: Create a Pom.xml for the Required Libraries
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/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.example</groupId>
<artifactId>SpringWebExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringWebExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<java-version>1.7</java-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>HelloWorld</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>SpringWebExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
We're using Spring 4.3.0 and Servlet 3.
Step 2: Creating the SpringConfig Class
As we want to do Java-based configuration, we will create a class called SpringConfig, where we will register all Spring-related beans using Spring's Java-based configuration style.
This class will replace the need to create a SpringApplicationContext.xml file, where we use two important tags
<context:component-scan/>
<mvc:annotation-driven/>
Please note that this class has to extend the
org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
class.
Let's see the class.
SpringConfig.java:
package com.example.anotatedconfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class SpringConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver viewResolver() {@Configuration
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Please note that here, we will use three different annotations at the top level. They will serve the purpose of the XML-based tags used earlier.
XML Tag | Annotation | Description |
<context:component-scan/> | @ComponentScan() | Scan starts from base package and registers all controllers, repositories, service, beans, etc. |
<mvc:annotation-driven/> | @EnableWebMvc | Enable Spring MVC-specific annotations like @Controller |
Spring config file | @Configuration | Treat as the configuration file for Spring MVC-enabled applications. |
Also, we use the @Bean tag to register ViewResolver. We use InternalResourceViewResolver.
Step 3: Replacing Web.xml
Create another class, which will replace our traditional web.xml. We use Servlet 3.0 and extend the org.springframework.web.WebApplicationInitializer
class.
WebServletConfiguration.java:
package com.example.anotatedconfiguration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebServletConfiguration implements WebApplicationInitializer{
public void onStartup(ServletContext ctx) throws ServletException {
AnnotationConfigWebApplicationContext webCtx = new AnnotationConfigWebApplicationContext();
webCtx.register(SpringConfig.class);
webCtx.setServletContext(ctx);
ServletRegistration.Dynamic servlet = ctx.addServlet("dispatcher", new DispatcherServlet(webCtx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
Here we provide our SpringConfig class and add DispatcherServlet, which acts as the FrontController of the Spring MVC application.
SpringConfig class is the source of Spring beans, before which we used contextConfiglocation.
Step 4: Create a Controller Class
Now we will create a Controller class, Which will take a parameter from request URL and greet a message in the browser.
package com.example.anotatedconfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class GreetController {
@RequestMapping(path= "/greet/{name}",method=RequestMethod.GET)
public String greet(@PathVariable String name, ModelMap model){
String greet =" Hello !!!" + name + " How are You?";
model.addAttribute("greet", greet);
System.out.println(greet);
return "greet";
}
}
Step 5: Create a JSP Page to Show the Message
So, with all the configuration
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<%@ page isELIgnored="false" %>
</head>
<h1>Welcome to Spring 4 and Servlet 3 Based Application</h1>
<body>
<div>
</div>
</body>
</html>
Please note that here that I use <%@ page isELIgnored="false" %>. If the JSTL version is old (before 1.2), it can’t evaluate ${} EL. If your JSTL version is 1.2, you can safely remove that tag.
Output:
http://localhost:8080/SpringWebExample/greet/shamik
Hello !!!shamik How are You?
Published at DZone with permission of Shamik Mitra, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments