springMVC ModelAttribute以及参数绑定

2018年03月05日 13:55 | 3542次浏览

一、前言

    https://www.vxzsk.com/599.html这个章节,我们讲解了Controller的几种返回类型:String(逻辑视图)、ModelAndView(渲染视图)、void(HttpServletRequest)、redirect(重定向)、forward(页面转发),以及Controller的四种参数转换方法:@InitBinder属性编辑器java文件与配置的方法、参数转换器关于没有没<mvc:annotation-driven>标签的两种配置方式。

 

二、@ModelAttribute

2.1@ModelAttribute在方法头上

注解@ModelAttribute 注解在方法头上,先于所有方法

    
    @ModelAttribute("itemtype")
    public Map<Object,Object> getItemtype(){
        Map<Object,Object> map=new HashMap<Object,Object>();
        map.put("1","商品类型1");
        map.put("2","商品类型2");
        return map;
    }

在页面上

	<select>
		<c:forEach items="${itemtype}" var="item">
			<option value="${item.key}">${item.value}</option>
		</c:forEach>
	</select>

没有任何Controller里面的方法执行商品类型,但是我们页面还是通过jstl拿到了它。用于完成一些公用数据的展示,选择等待。

springMVC

2.2@ModelAttribute在方法参数上 可用于参数验证

注解@ModelAttribute放在方法参数上,可以了让参数回传!!!

    /**
     * 修改商品属性
     * @return
     */
    @RequestMapping("/editItemSubmit")
    public String editItemSubmit(Integer id,@ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom) throws Exception {
        itemsService.updateItem(id, itemsCustom);
        //返回修改页面
        return "order/editItem";
    }

注意:我们的URl没有跳转,只是页面跳到了修改页面,但是数据依然可以显示在页面上。(是不是想到参数验证??不跳页面)

三、controller批量参数

前面我们已经讲解了一些传递的参数,参数都只是单个实体、基本类型、map,我们来看看如果传递批量数据到我们的前端控制器。

3.1 简单数据类型--数组[ ]

1、Controller类编写

   /**
     * 删除商品(基本类型的数组)
     * @param delete_id
     * @return
     * @throws Exception
     */
    @RequestMapping("/deleteItems")
    public String deleteItems(Integer[] delete_id) throws Exception {
        //删除方法我就不写了
        for (Integer integer : delete_id) {
            System.out.println("需要删除的id:"+integer);
        }
        return "success";
    }

2、JSP页面编写:

我们只需要步骤如下

1、标出我们选择对象 

<td><input type="checkbox" name="delete_id" value="${item.id}"/></td>

2、获取选择值:

	<script type="text/javascript">
		//--------------------------------------批量删除商品----------------------------------------------
		function deleteItems(){
			document.itemsForm.action="${pageContext.request.contextPath }/items/deleteItems";
			document.itemsForm.submit();
		}

	</script>

3、提交到我们的Controller方法

<input type="button" value="批量删除"  onclick="deleteItems()"/>

4、注意:我们的name就是一个键,所以接受的方法里面,两个键值必须都是delete_id

在js或者ajax提交,我们可以定义一个数组:var delete_id=[12,23,5,3,25,98,76,54,56,76];一样的可以

全部editItemsList.jsp如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"  %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询商品列表</title>
	<script type="text/javascript">
		//--------------------------------------批量删除商品----------------------------------------------
		function deleteItems(){
			document.itemsForm.action="${pageContext.request.contextPath }/items/deleteItems";
			document.itemsForm.submit();
		}

	</script>
</head>
<body> 
<form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/><input type="button" value="批量删除"  onclick="deleteItems()"/>
	<select>
		<c:forEach items="${itemtype}" var="item">
			<option value="${item.key}">${item.value}</option>
		</c:forEach>
	</select>
</td>

</tr>
</table>
商品列表:33
<table width="100%" border=1>
<tr>
	<td>商品名称</td>
	<td>商品价格</td>
	<td>生产日期</td>
	<td>商品描述</td>
	<td>操作</td>
</tr>
	<c:forEach items="${itemsList}" var="item">
		<tr>
			<td><input type="checkbox" name="delete_id" value="${item.id}"/></td>
			<td>${item.name}</td>
			<td>${item.price}</td>
				<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
				<td>${item.detail}</td>
			<td><a href="${pageContext.request.contextPath }/items/editItems?id=${item.id}">修改</a></td>

		</tr>

	</c:forEach>
</table>
</form>
</body>

</html>

3.2 JAVA类型的批量对象--List[ Object]

1、Controller类编写

参数类

package com.ycy.dto;  
  
import java.io.Serializable;  
import java.util.List;  
  
/**  
 * Created by Administrator on 2015/9/28 0028.  
 */  
public class ItemsCustomVo  implements Serializable{  
  
    private List<ItemsCustom>  itemsList;  
  
    public List<ItemsCustom> getItemsList() {  
        return itemsList;  
    }  
  
    public void setItemsList(List<ItemsCustom> itemsList) {  
        this.itemsList = itemsList;  
    }  
}


Controller类

/**  
     * 查询批量习惯的商品  
     * @param httpServletRequest  
     * @param httpServletResponse  
     * @return  
     * @throws Exception  
     */  
    @RequestMapping("/editItemsList")  
    public ModelAndView editItemsList(javax.servlet.http.HttpServletRequest httpServletRequest,  
                                   javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {  
        //如果是转发:httpServletRequest的数据是可以共享的  
  
        //商品列表  
        List<ItemsCustom> itemsList = itemsService.findtemsList(null);  
        //创建modelAndView准备填充数据、设置视图  
        ModelAndView modelAndView = new ModelAndView();  
        //填充数据  
        modelAndView.addObject("itemsList", itemsList);  
        //视图  
        modelAndView.setViewName("order/editItemsList");  
  
        return modelAndView;  
    }  
  
    /**  
     * 批量修改数据(JAVAList对象)  
     * @param itemsCustomVo  
     * @return  
     * @throws Exception  
     */  
    @RequestMapping("/editItemsListSubmit")  
    public String editItemsListSubmit(ItemsCustomVo itemsCustomVo) throws Exception{  
        //方法我就不写了  
        List<ItemsCustom>  itemsCustoms=itemsCustomVo.getItemsList();  
        for (ItemsCustom itemsCustom : itemsCustoms) {  
            System.out.println("需要修改的id:"+itemsCustom.getName());  
        }  
        return "success";  
    }


2、JSP编写

1】批量修改页面的编写:editItemsList.jsp 查询数据

2】标出所有对象,根据jstl标签([]里面是迭代变量,就是下标),定义好name属性:itemList键与我们接受键相同,或者我们用@RequestParam来保证参数正确

name="itemsList[${s.index}].name"

3】提交到Controller方法

editItemsList.jsp 页面如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>批量修改商品查询</title>
<script type="text/javascript">
//修改商品提交
function updateItems(){
	
	//将form的action指向删除商品的地址
	document.itemsForm.action="${pageContext.request.contextPath }/items/editItemsListSubmit";
	
	//进行form提交
	document.itemsForm.submit();
	
}
</script>
</head>
<body> 
<form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItem" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>
商品类别:
<select>
	<c:forEach items="${itemsType }" var="item">
			<option value="${item.key }">${item.value }</option>
	
	</c:forEach>
	
</select>
</td>
<td><input type="submit" value="查询"/>
<input type="button" value="批量修改提交" onclick="updateItems()"/>
</td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>	
	<td>商品名称</td>
	<td>商品价格</td>
	<td>生产日期</td>
	<td>商品描述</td>
	<td>操作</td>
</tr>
<c:forEach items="${itemsList}" var="item" varStatus="s">
<tr>
	<td><input type="text" name="itemsList[${s.index }].name" value="${item.name }"/></td>
	<td><input type="text" name="itemsList[${s.index }].price" value="${item.price }"/></td>
	<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
	<td>${item.detail }</td>
	
	<td><a href="${pageContext.request.contextPath }/items/editItems?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

</table>
</form>
</body>

</html>


小说《我是全球混乱的源头》

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程