Spring MVC Java Configuration Example
This tutorial shows how to build a basic Spring MVC Web Application. We start by defining the project structure. Next, we add the project’s dependencies via Apache Maven. Then we create a simple controller using the @Controller annotation which we configure with Spring MVC Java Configuration. Afterwards, we configure the servlet environment using java configuration. This means that we are completely removing the web.xml file. Finally, we build a simple view, topped of with a simple demo.
Project Structure
Make sure your project looks similar to the following structure.
src |--main | +--java | +--com | +--memorynotfound | +--config | |--ServletInitializer.java | |--WebConfig.java | +--controller | |--HomeController.java | +--resources | +--webapp | +--WEB-INF | +--views | |--index.jsp pom.xml
Maven Dependencies
We are working with Apache Maven for our project management. Simply add the necessary dependencies to the project and Maven will resolve and manage all the dependencies automatically. Below is the pom.xml file for our project.
Notice we included the maven-war-plugin. Since we are configuring our application using Java Configuration, we don’t need the web.xml anymore. In order for our project to build successfully, we need to instruct Maven to ignore the web.xml file. We do this by setting the failOnMissingWebXml element to false.
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.memorynotfound.spring.mvc</groupId> <artifactId>java-config</artifactId> <version>1.0.0-SNAPSHOT</version> <name>SPRING-MVC - ${project.artifactId}</name> <url>https://memorynotfound.com</url> <packaging>war</packaging> <properties> <encoding>UTF-8</encoding> <spring.version>4.2.6.RELEASE</spring.version> </properties> <dependencies> <!-- spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- servlet api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
Creating the Controller
By annotating the class with @Controller annotation – which is a stereo type annotation used to indicate that this is a controller – the dispatcher servlet will automatically map the methods defined in the class using the @RequestMapping annotation.
The @RequestMapping annotation maps the URL’s onto particular classes or methods. The class-level annotation is mostly used to map a specific request path onto a form controller, whereas a method-level annotations narrows the mapping for a specific HTTP request method like (GET, PUT, POST and DELETE). In this example, we populate the Model map – which is basically a map for the request attributes – with a key called message and a simple string value.
The return value is the name of the view. The InternalResourceViewResolver will prefix and suffix the return value to form the real path of the view file name.
package com.memorynotfound.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping("/") public class HomeController { @RequestMapping(method = RequestMethod.GET) public String index(ModelMap model){ model.addAttribute("message", "Spring MVC Java Configuration Example"); return "index"; } }
Configure Spring MVC with Java Config
The @Configuration annotation indicates that this class declares one or more @Bean methods and may be processed by the spring container to generate bean definitions and service requests for those beans at runtime.
The @EnableWebMvc enables support for the @Controller annotation that uses @RequestMapping to map incomming requests to specific methods.
The @ComponentScan will instruct spring which packages it may scan to discover spring annotated beans.
The InternalResourceViewResolver will prefix and suffix the return value of the controller to construct the real path of the view file.
package com.memorynotfound.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.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan({"com.memorynotfound"}) public class WebConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
Configuring the Dispatcher Servlet
The DispatcherServlet acts like a front-controller and is used to dispatch the requests to the appropriate controller methods. We configure it by extending the AbstractAnnotationConfigDispatcherServletInitializer class which is a base class for the WebApplicationInitializer, this will configure the servlet context programatically. We need to tell it where the location of our Spring MVC Java Configuration file is located. We do this by registering the class – of our java configuration – in the getServletConfigClasses method.
package com.memorynotfound.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { WebConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Class<?>[] getRootConfigClasses() { return null; } }
Creating the View
Finally, we build a simple view displaying the value of the message attribute we added earlier in the controller.
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Spring MVC Java Configuration Example</title> </head> <body> ${message} </body> </html>
Demo
URL: http://localhost:8081/spring-mvc-java-config/
Download
From:一号门
Previous:Spring MVC XML Configuration Example
COMMENTS