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.

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar