spring 3 not rendering model in jsp

2019-08-30 18:42发布

问题:

I am a bit disapointed concerning Spring 3 not rendering my model in a jsp using Expression Language and I have to admit that I dont understand why. If anyone could help me understanting why I can't make it work it will be really great.

Here's my context:

My controller have a method (called by ajax from my client) returning a jsp fragment:

@RequestMapping(value = "/datagrid/getGoatCard", method = RequestMethod.POST)
public String getGoatCard(@RequestParam Long id,
        @ModelAttribute("goat") Goat goat) {
    goat = goatDataService.findGoatById(id);
    return "goatCard";
}

I call this method with a requestParam allowing hibernate to retrieve the desired Bean (the model contains all the requiered data, it has been checked).

Then this method retruns a jsp named "goatCard"; here's the jsp code:

<input name="goat.goatName" type="hidden" value="${goat.goatName}"/>

(this isn't the whole page code, cause this won't be easy to read if too many code is presented. My jsp contains JQuery easyui and highcharts javaScript librairies)

I though that the annotation @ModelAttribute("goat") linked the model called "goat" to my jsp allowing to render the model using EL but it doesn't seem so.

Does anybody have any idea, perhaps it just a little thing that I did wrong but I don't see which one!!!!

回答1:

@ModelAttribute is used for retrieving form model rather than setting to be displayed in JSP. If you need to display data in JSP, you have to add the data into Model first.

@RequestMapping(value = "/datagrid/getGoatCard", method = RequestMethod.POST)
public ModelAndView getGoatCard(@RequestParam Long id) {
    ModelAndView mv = new ModelAndView("goatCard");
    Goat goat = goatDataService.findGoatById(id);
    mv.addObject("goat",goat);
    return mv;
}

And then goat is available in JSP file. By the way, for retrieving data, better to use RequestMethod.GET.



回答2:

Thank's a lot for your help. Just an answer to update your code. As I use Spring 3, it is better to write

@RequestMapping(value = "/datagrid/getGoatCard", method = RequestMethod.POST)
public String getGoatCard(@RequestParam Long id,
        Model model) {
    model.addAttribute("goat", goatDataService.findGoatById(id));
    return "goatCard";
}

It's just to fit more to the preconisation of Spring Foundation (I agree this lead to the same result, but SpringSource recommend the use of String return instead of mav).

Again thanks for your help