This tutorial shows how to create a Spring MVC Annotation Example or build a basic Spring MVC Web Application without web.xml configuration. Spring MVC 4 is a main part of Spring Frameworks and is great for you to build web applcation.
Table of contents:
1. Project Structure
2. Maven Dependencies
3. Create the Controller
4. Configure Spring MVC with Java Annotation Configuration
5. Configure the Dispatcher Servlet
6. Create the View
7. Deploy Spring MVC Annotation Example
Other interesting posts you may like
Project Structure
Make sure your project looks similar to the following structure.
Maven Dependencies
We are using the latest version of Spring MVC in this example. One more thing, we are configuring our application using Java Annotation Configuration, we don’t use the web.xml anymore. We need to instruct Maven to ignore the web.xml file by setting the failOnMissingWebXml element to false. Below is the pom.xml file for our project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<?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.javabycode.spring.mvc</groupId> <artifactId>java-config</artifactId> <version>1.0.0-SNAPSHOT</version> <name>SPRING-MVC - ${project.artifactId}</name> <packaging>war</packaging> <properties> <encoding>UTF-8</encoding> <spring.version>4.3.0.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> <finalName>spring-mvc-annotation-example</finalName> <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> |
Create the Controller
By annotating the class with @Controller annotation. It means that a class serves the role of a controller.
The dispatcher servlet will automatically map the methods defined in the class using the @RequestMapping annotation.
The @RequestMapping annotation to map URLs such as “/” onto an entire class or a particular handler method. In our case, we have applied it on class level too, which says that this class is default handler for all HTTP requests of type ‘/’. @RequestMapping have several attributes [value,method,params,..] which can be used to narrow down the mapping to more specific selection.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javabycode.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("/mycontroller") public class MyController { @RequestMapping(method = RequestMethod.GET) public String index(ModelMap model){ model.addAttribute("message", "This is the Spring MVC Annotation Example"); return "index"; } } |
Configure Spring MVC with Java Annotation Configuration
The @Configuration annotation indicates that the class can be used by the Spring IoC container as a source of bean definitions.
The @EnableWebMvc is equivalent to
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. Here The real path of the view file is /WEB-INF/views/index.jsp.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.javabycode.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; @EnableWebMvc @Configuration @ComponentScan({"com.javabycode"}) public class MyWebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } } |
Configure the Dispatcher Servlet
The DispatcherServlet is used to dispatch the requests to the appropriate controller methods. We configure it by extending the AbstractAnnotationConfigDispatcherServletInitializer. Then we register the Spring MVC java Configuration file (Here is MyWebMvcConfig class) with DispatcherServlet in the getServletConfigClasses method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.javabycode.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { MyWebMvcConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override protected Class<?>[] getRootConfigClasses() { return null; } } |
Create the View
Finally, we build a simple view displaying the value of the message attribute we added earlier in the controller.
1 2 3 4 5 6 7 8 9 10 11 |
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>This is the Spring MVC Annotation Example</title> </head> <body> ${message} </body> </html> |
Deploy Spring MVC Annotation Example
After building the project by maven we deploy the file war on application server (Tomcat 8 for example). Access the address to see how it works:
URL: http://localhost:8080/spring-mvc-annotation-example/mycontroller
Here is the screen shoot
Download complete source code of example, please click link below
Spring-MVC-Annotation-Example.zip (627 downloads)
Source code on Github https://github.com/javabycode/spring-mvc-annotation-example