Pass data from Spring controller to JSP

This tutorial describes how to pass data from a Spring controller to a JSP view.

If you’re still using servlets, then check our “Pass data from servlet to JSP” tutorial.

Spring MVC provides a very convenient way of doing this by exposing objects like ModelMap and ModelAndView.

1- ModelMap

Spring MVC exposes a utility class called ModelMap which implicitly extends a LinkedHashMap.

In order to pass data from controller to JSP, all you have to do is add a ModelMap argument to your controller method and then populate it inside your method body using the generic addAttribute() method.

In the following example, we pass a welcome message from the controller by adding a message attribute to the model.

You can use addAttribute() to pass any type of data like objects, arrays, lists and maps.

When using ModelMap, you have to explicitly return the name of the JSP view at the end of your controller method.

Now, inside your JSP, you can read the message attribute in 2 ways:

2- ModelAndView

ModelAndView interface is used to pass data attributes and JSP view name at one shot, unlike ModelMap which is only used for passing attributes.

When using ModelAndView, your controller method should return a ModelAndView object instead of a String. Here below, we write the same above example using ModelAndView:

As noticed, we pass the view name as an argument to the ModelAndView constructor, then we pass data attributes through the addObject() method.

ModelAndView interface is not defined as an argument to the controller method, rather it’s instantiated inside the method body.

4.3 3 votes
Article Rating

Hussein Terek

Owner of, I have a passion for software engineering and everything related to Java environment.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
7 months ago

This is going to refresh the page, right? How to pass data from Controller to JSP without reloading the page or redirect to any other JSP? Is this possible without ajax? I am hitting the controller from a form.