我有一个使用JSP进行视图技术的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
是字符串(并且buzz
是int
),我将如何在HTML和JS中打印它们:
<script type="text/javascript>
alert("Buzz is " + buzz);
</script>
<div>
<h2>The type of fruit is ??? fruitType ???</h2>
</div>
预先感谢。
弹簧控制器将视图对象存储在页面上下文中,并使用el:
访问它们<div>
<h2>The type of fruit is ${fruitType}</h2>
</div>
这在Oracle Java EE教程中以及介绍性Spring MVC教程中进行了描述。