标签:springmvc
Map,即java.util.Map,在springMVC中起到了至关重要的作用。它是架起视图和Model层的一座桥梁。
在RequestMap标记的任何一个方法,都可以使用Map< String, Object >
作为入参,这个map最终会自动添加到view的请求域中,在view中可以使用${key }或${requestScope.key }将model取出。
注:Map中的key必须是String类型的,因为这个map相当于映射了请求域中的键值对。
下面看一个例子:
@RequestMapping("/emp")
public String showEmployee(Map<String, Object> map){
List<Employee> employees = employeeDao.selectAll();
map.put("employees", employees);
return "list";
}
在这个路径下,将所有employee取出来放到map中,然后框架会带着这个map进入list.jsp这个view中去。
在list.jsp中引用:
<c:if test="${empty requestScope.employees}">
没有信息
</c:if>
<c:if test="${!empty requestScope.employees }">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th>Department</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="emp" items="${requestScope.employees }" >
<tr>
<th>${emp.id}</th>
<th>${emp.name}</th>
<th>${emp.gender==0?‘female‘:‘male‘}</th>
<th>${emp.age}</th>
<th>${emp.department.name}</th>
<th><a href="">edit</th>
<th><a href="">delete</a></th>
</tr>
</c:forEach>
</table>
</c:if>
抛去标签先不说,对于key=employees的这个model来说,取出来的时候就用
下面介绍标签语言:
jstl可以以标签的形式进行逻辑控制。
使用该标签配合EL表达式可以很方便的实现对model的一些操作。这些操作往往是对model的信息进行遍历显示等等。
在view中使用jstl需要在xml头部引入jstl标准库:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
才能使用上述例子中的操作。
jstl还有很多有用的工具,比如form
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
使用这种form能够非常方便的跟对象映射起来。
正如SpringMVC之一中提到的@ModelAttribute
标签标记过的方法。只不过是,原生的form可以不用ModelAttribute进行“预先映射实体”,仅仅是在有需要的时候进行一下预提取(见SpringMVC之一中@ModelAttribute的例子);但是在jstl中的form,springMVC默认其必须有一个实体进行映射,即在显示表单的时候,表单所对应的实体也必须放在requestScope中或者sessionValue中去。在requestScope的情况,就用到了上述的map。在对应的Controller方法中,将表单实体放入map,然后返回view名称。框架会自动带着map传入到对应的view页面。
view页面包含的这个jstl表单也有一些要求:
参照下面的例子,一一列举:
<form:form action="input" method="POST" modelAttribute="employee">
Name: <form:input path="name" />
<br>
Age: <form:input path="age"/>
<br>
Gender:<form:radiobuttons path="gender" items="${genders}"/>
<br>
DepartmentName:<form:select path="department.id" items="${departments}"
itemLabel="name" itemValue="id"/>
<br>
<input type="submit" value="Submit"/>
</form:form>
<form:input path="age"/>
。对于级联属性,则对应级联的属性名。如例子中的<form:select path="department.id" items="${departments}"
以上例子中,form提交之后会到如下的方法中(以Post提交):
入参中的employee正是map中放入的“key”对应的实例employee。
@RequestMapping(value="/input", method=RequestMethod.POST)
public String save(Employee employee){
employeeDao.save(employee);
return "redirect:/emp";
}
最终重定向到/emp的页面中显示所有employee。
附:
SpringMVC 提供了多个表单组件标签,如
< form:input />、< form:select /> 等,用以绑定表单字段的
属性值,它们的共有属性如下:
Spring MVC 中的 forward 和 redirect
这两篇文章短小但重点突出。
标签:springmvc
原文地址:http://blog.csdn.net/langduhualangdu/article/details/46475475