我有一个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页面中,我需要访问fruitType
和buzz
变量(在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>
提前致谢。
答案 0 :(得分:2)
Spring控制器将视图对象存储在页面上下文中,并使用EL:
访问它们<div>
<h2>The type of fruit is ${fruitType}</h2>
</div>
这在Oracle Java EE Tutorial中以及介绍性Spring MVC tutorial中进行了描述。