Heshan Perera
Heshan Perera

Reputation: 4630

Spring MVC: How to retrieve data apart from the Model submitted to a view

I have the following requirement. I submit a Model object to a view as follows...

@RequestMapping(value ="/addItem", method = RequestMethod.GET)
     public ModelAndView showContacts() {           
         ModelAndView modelAndView = new ModelAndView("addItem", "command", new Item());
         return modelAndView;
     }

But on post, I need to retrieve a value apart from the "Item" object (model) that is returned to me. I can't have this variable be a part of the Item model object because it does not belong there. But I need it returned in order to act on that value. How can I get about doing this ?

I.e. In my JSP file, I have the following fields...

<form:input type="text" path="val1"/>
<form:input type="text" path="val2"/>
<form:input type="text" path="val3"/>

Out of the above, only fields val1 and val2 have mappings to the Item object, where as val3 does not. Nevertheless, I need the value of val3 passed back to my controller as well. The code I have right now to handle the POST is as follows, but I can't figure out how to get the value for val3. The code does not compile right now because it says that there is no field or appropriate getter method in the Item class for val3.

@RequestMapping(value = "/postItem", method = RequestMethod.POST)
    public String postItem(@ModelAttribute("item") Item item , BindingResult result) {
        logger.info("Post Item:");
        return "home";
    }

How can I modify the above code to suite my requirement ?

Some guidance on this matter will be highly appreciated.

Upvotes: 2

Views: 2709

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96385

You can pass a map as the model, and include all sorts of different things in there. You are not limited to a single domain object, that constructor is there as a convenience, it is not the only way to do it. There is a variation of the constructor:

public ModelAndView(Object view,
                    Map model)

    Create a new ModelAndView given a View object and a model.

    Parameters:
        view - View object to render (usually a Servlet MVC View object)
        model - Map of model names (Strings) to model objects (Objects). 
        Model entries may not be null, but the model Map may be null if 
        there is no model data.

Upvotes: 1

Related Questions