Spring MVC ModelMap

In this post , we will see how to use ModelMap in Spring MVC.

Spring MVC tutorial:

ModelMap object is used to pass multiple values from Spring MVC controller to JSP .

Some basics about Spring MVC ModelMap class:

  • ModelMap class subclasses LinkedHashMap. It add some methods for convenience.
  • It provides addAttribute method to put key value pair. This method return ModelMap objects that can be used for chaining.
  • ModelMap uses as generics.
  • ModelMap checks for null values.

Example:

Prerequisite:

You need to create spring mvc hello world example first.

Once you are done with spring mvc sample project. We need to add or modify following files.

  • Make changes to HelloWorldController.java
  • Modify index.jsp
  • Modify hello.jsp

Thats all we need to do to demonstrate Spring MultiActionController example.

1) change HelloWorldController.java as below

package org.arpit.java2blog.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {

 @RequestMapping("/helloworld")
 public String hello(ModelMap map) {

  String helloWorldMessage = "Hello world from java2blog!";
  String welcomeMessage = "Welcome to  java2blog!";
  map.addAttribute("helloMessage", helloWorldMessage);
  map.addAttribute("welcomeMessage", welcomeMessage);

  return "hello";
 }
}

We have added two attributes to ModelMap and they will be used in jsp with helloMessage and welcomeMessage

2) Modify index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>




HelloWorld


Click here to read hello and welcome message

3)Modify hello.jsp in /WEB_INF folder.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Hello


${helloMessage}

${welcomeMessage}

4) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build
5) Provide goals as clean install (given below) and click on run

Run the application

6) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

7) You will see below screen:

When you click on  link, you will get below screen

We are done with Spring MVC ModelMap example. If you are still facing any issue, please comment.
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.