从Spring MVC控制器注入JSP

时间:2012-12-20 16:14:11

标签: java javascript jsp spring-mvc

我有一个Spring MVC Web应用程序,它使用JSP作为View技术。在控制器中,我将值注入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是一个字符串(而buzzint),我将如何在HTML和JS中打印它们:

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

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

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

访问它们
<div>
    <h2>The type of fruit is ${fruitType}</h2>
</div>

这在Oracle Java EE Tutorial中以及介绍性Spring MVC tutorial中进行了描述。