从Spring MVC控制器注入JSP


问题内容

我有一个将JSP用于View技术的Spring MVC
Web应用程序。在控制器中,我正在将值注入到ModelAndView对象中,然后将使用该对象(与相应的JSP一起)来帮助构造最终的HTML以返回到客户端。

控制器:

@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;
}

该控制器(处理/widgets.html请求)进行一些查找并返回注入的AllWidgets.jsp页面。在该JSP页面中,我需要同时访问fruitType和和buzz变量(在HTML和JS内),但不确定如何执行此操作。例如,假设fruitType是一个String(并且buzz是一个int),我将如何在HTML和JS中同时打印它们:

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

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

提前致谢。


问题答案:

Spring控制器将视图对象存储在页面上下文中,并使用EL对其进行访问:

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

这在Oracle Java
EE教程
以及Spring
MVC
入门教程中都有描述。