3
votes

I have a Spring MVC web app that uses JSP for the View technology. In the controller I am injecting values into the ModelAndView object that will then be used (with the respective JSP) to help construct the final HTML to return to the client-side.

The controller:

@RequestMapping(value = "/widgets.html", method = RequestMethod.POST)
public ModelAndView widgets(@Model Fruit fruit, @RequestParam("texture") String texture) {
    ModelAndView mav = new ModelAndView();

    // The name of the JSP to inject and return.
    max.setViewName("widgets/AllWidgets");

    int buzz = calculateBuzzByTexture(texture);

    mav.addObject("fruitType", fruit.getType());
    mav.addObject("buzz", buzz);

    return mav;
}

This controller (which handles /widgets.html requests) does some lookups and returns the injected AllWidgets.jsp page. In that JSP page, I need to get access to both the fruitType and buzz variables (inside both HTML and JS), but not sure how I can do this. For instance, assuming fruitType is a String (and buzz is an int), how would I print them in both HTML and JS:

<script type="text/javascript>
    alert("Buzz is " + buzz);
</script>

<div>
    <h2>The type of fruit is ??? fruitType ???</h2>
</div>

Thanks in advance.

1

1 Answers

2
votes

The Spring controller stores the view objects in the page context, and they are accessed using EL:

<div>
    <h2>The type of fruit is ${fruitType}</h2>
</div>

This is described in the Oracle Java EE Tutorial, and also in the introductory Spring MVC tutorial.