我正在阅读 spring MVC 教程并遇到了 ModelAndView。
我的 JSP 视图如下所示,
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC </title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${student.getName()}</td>
</tr>
<tr>
<td>Age</td>
<td>${student.getAge()}</td>
</tr>
<tr>
<td>ID</td>
<td>${student.getBranch()}</td>
</tr>
</table>
</body>
</html>
当我在控制器中设置属性名称和属性值时,它起作用了,如下所示,
ModelAndView mv = new ModelAndView();
mv.setViewName("result");
Student student = new Student("arun2", "CSE", 22);
mv.addObject("student",student);
return mv;
然后我遇到了其他重载方法ModelAndView.addObject(Object attributeValue)
,我尝试只设置属性值mv.addObject(student);
但是这次它没有在浏览器中显示学生详细信息。
我的问题:
mv.addObject(student);
。我浏览了javadocs,但没有找到任何可以让我理解的东西。
是的,你可以这样做并访问参数,但需要注意一些。
在ModelAndView处检查 addObject 的 API ,它将显示如下方法:
然后我们看一下ModelMap.addAttribute(Object)的定义
它示出了使用一个生成的名称,定义生成的名称列示如下:
所以,如果你只是想使用这个mv.addObject(student)
方法,你可以在你的jsp页面中访问数据,如下所示:
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC </title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${student.name}</td>
</tr>
<tr>
<td>Age</td>
<td>${student.age}</td>
</tr>
<tr>
<td>ID</td>
<td>${student.branch}</td>
</tr>
</table>
</body>
</html>
如果对象是一个Group
类,那么你可以通过${group.name}
并注意ModelAndView来自org.springframework.web.servlet.ModelAndView
另外,我建议您使用EL 表达式直接访问您的 jsp 页面中的数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句