3

我有一个使用 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 页面中,我需要同时访问fruitTypebuzz变量(在 HTML 和 JS 中),但不知道如何做到这一点。例如,假设fruitType是一个字符串(并且buzz是一个int),我将如何在 HTML 和 JS 中打印它们:

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

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

提前致谢。

4

1 回答 1

2

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

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

Oracle Java EE 教程以及Spring MVC入门教程中对此进行了描述。

于 2012-12-20T16:21:37.793 回答