Spring ModelAndView
last modified October 18, 2023
Spring ModelAndView tutorial shows how to use ModelAndView in a controller in a Spring web application.
Spring is a popular Java application framework for creating enterprise applications.
ModelAndView
ModelAndView
is a holder for both Model
and
View
in the web MVC framework. These two classes are distinct;
ModelAndView
merely holds both to make it possible for a controller
to return both model and view in a single return value.
The view is resolved by a ViewResolver
object; the model is data
stored in a Map
.
Spring ModelAndView example
The following application uses ModelAndView to return a model and a view in one step in a Spring controller. We use Freemarker for view resolving.
pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ ├───config │ │ │ MyWebInitializer.java │ │ │ WebConfig.java │ │ └───controller │ │ MyController.java │ └───resources │ │ logback.xml │ └───templates │ index.ftlh │ show.ftlh └───test └───java
This is the project structure.
<?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.zetcode</groupId> <artifactId>springmodelandview</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <spring-version>5.3.23</spring-version> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.3.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.49.v20220914</version> </plugin> </plugins> </build> </project>
In the pom.xml
we have the necessary dependencies.
<?xml version="1.0" encoding="UTF-8"?> <configuration> <logger name="org.springframework" level="ERROR"/> <logger name="com.zetcode" level="INFO"/> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n </Pattern> </encoder> </appender> <root> <level value="INFO" /> <appender-ref ref="consoleAppender" /> </root> </configuration>
The logback.xml
is a configuration file for the Logback logging library.
package com.zetcode.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @Configuration public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
MyWebInitializer
registers the Spring DispatcherServlet
, which
is a front controller for a Spring web application.
@Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; }
The getServletConfigClasses
returns a web configuration class.
package com.zetcode.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.WebMvcConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"com.zetcode"}) public class WebConfig implements WebMvcConfigurer { @Bean public FreeMarkerViewResolver freemarkerViewResolver() { var resolver = new FreeMarkerViewResolver(); resolver.setCache(true); resolver.setSuffix(".ftlh"); return resolver; } @Bean public FreeMarkerConfigurer freemarkerConfig() { var freeMarkerConfigurer = new FreeMarkerConfigurer(); freeMarkerConfigurer.setTemplateLoaderPath("classpath:/templates/"); return freeMarkerConfigurer; } }
WebConfig
configures FreeMarker template engine. We set the
template files location to templates
directory on the classpath.
(The resources
is on the classpath.)
package com.zetcode.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Controller public class MyController { @GetMapping(value = "/") public String home() { return "index"; } @GetMapping(value = "/show") public ModelAndView show() { var mav = new ModelAndView(); var now = LocalDateTime.now(); var formatter = DateTimeFormatter.ISO_DATE_TIME; var dateTimeFormatted = formatter.format(now); mav.addObject("now", dateTimeFormatted); mav.setViewName("show"); return mav; } }
MyController
provides two GET mappings.
@GetMapping(value = "/show") public ModelAndView show() {
The show
method returns a ModelAndView
.
var mav = new ModelAndView(); var now = LocalDateTime.now(); var formatter = DateTimeFormatter.ISO_DATE_TIME; var dateTimeFormatted = formatter.format(now); mav.addObject("now", dateTimeFormatted); mav.setViewName("show"); return mav;
A ModelAndView
is created and filled with data. The data
is a formatted datetime object. The view name is set with setViewName
.
Spring resolves the view name to show.ftl
.
<!DOCTYPE html> <html> <head> <title>Home</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p> <a href="show">Show today's datetime</a> </p> </body> </html>
The home page contains a link to show today's datetime.
<!DOCTYPE html> <html> <head> <title>Today's date</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p> Today is: ${now} </p> </body> </html>
In the show.ftlh
view we show the current datetime with ${}
syntax.
$ mvn jetty:run
We run the server and locate to localhost:8080
to get the home page,
which has the link.
In this article we have organized model and view with ModelAndView
.
Author
List all Spring tutorials.