Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting JSP from Spring MVC controller

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.

like image 920
IAmYourFaja Avatar asked Dec 01 '25 09:12

IAmYourFaja


1 Answers

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.

like image 164
parsifal Avatar answered Dec 03 '25 22:12

parsifal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!