Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Why model should be a map object using Sparks micro-framework?

Hello everyone,

post("/sign-in",(req,res) -> { Map<String,String> model = new HashMap<>(); model.put("username",req.queryParams("username")); return new ModelAndView(model, "sign-in.hbs"); }, new HandlebarsTemplateEngine());

I dont get it why model should be a map object. What is the logical explanation of why a model should be a map-object?

How ModelAndView handles the value we are passing in model parameter in order to be corresponded to the template(View)?

Thanks in advance, Anestis

Gábor Molnár
Gábor Molnár
9,928 Points

It's really simple, you should imagine everything as a key-value pair what you want to push to the template. And of course the Map data structure is best for this "operation". We store key-value pairs in Maps. There are not only one Map implementation. Map is just an interface, a pattern of a data structure. In your code, you use HashMap as an implementation of Map. There are some others, and you can do your own implementation too. You should check them out. One thing you should know, you can give any type that you want to store in Map. E.g. Map<String,Integer>, Map<Integer, YourOwnClassName>, Map<String, Object>. If you would like to use map a more flexible way in your routes, just use the last one. In the java world, everything is an Object, so you can pass to the template every single type that you want. The first type should be String because that will be the variable name in the template that references to the Object what you try to reach.

2 Answers

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

Hello Anestis Kallinikos ,

It is not necessary to code the model as Map, but as Gábor Molnár said, it is needed to be parsed as a key-value pair. i coded mine as a JSON representation, you know... as an object with an array inside it and more variables inside and i was able to pass the variables successfully, but a Map would be a quicker way. i just wanted to play with many things, to understand whats you are trying to understand now by yourself. :)

Got it, thanks Gabor and Konstantine! :)