San
San

Reputation: 161

Populate data in spring model

I have kept a map in the page model. While invoking the page, am fetching few items from database and will keep that in the map so that i will use it in the JSP. Mainly these items are used for populating options in dropdown.

@RequestMapping(value = "/initSystemPage")
public String initSystemPage(@ModelAttribute("systemModel") SystemModel systemModel, ModelMap modelMap) {

    Map<String, List<DropdownVO>> data = ** fetch items from database **;
    systemModel.setData(data);

    return "system";
}

Upon invoking the screen, i can get the items from the model and populate the values in the dropdown. So far fine. but the issue happens if i do any action like submitting the form. As am not keep an element in the JSP corresponding to the data attribute, upon submitting the form dropdown data is not mapped to model hence it is not available in the JSP after page refresh.

I dont want to populate the items in model in every action methods. if i keep the data in session attributes, is it possible to do the populate in a common method that need to be invoked in all actions? something like init-binder

Upvotes: 1

Views: 1196

Answers (1)

ekem chitsiga
ekem chitsiga

Reputation: 5753

If you want to keep your current design you can make use of @SessionAttributes annotation at class level to ensure that your systemModel attribute is stored in session and is accessible for subsequent requests. However make sure that you clear the attribute when you have completed form processing using SessionStatus. For example

@Controller
@SessionAttributes("systemModel")
public SystemPageController{

@RequestMapping(value = "/initSystemPage" , method = RequestMethod.GET)
public String initSystemPage(@ModelAttribute("systemModel") SystemModel systemModel, ModelMap modelMap) {

    Map<String, List<DropdownVO>> data = ** fetch items from database **;
    systemModel.setData(data);

    return "system";
}
}

Alternatively you can use @ModelAttribute annotation to indicate methods which should be called for every request for the Controller to add model data.

@ModelAttribute("systemModel")
public SystemModel populateSystemModel(){
   //code to populate and return
}

The signature is very flexible. You can include most parameters used with @RequestMapping methods such as HttpServletRequest @RequestParam , @PathVaribale etc

Upvotes: 1

Related Questions