SpringMvc绑定字符串数组和List参数

来源:互联网 发布:16进制转换10进制算法 编辑:程序博客网 时间:2024/05/17 20:25

前言

  • 上篇文章小编简单介绍了SpringMvc中默认支持的参数绑定和pojo参数绑定,现在小编继续介绍字符串数据和List绑定。

1、字符串数组

需求

  • 当我们在页面批量删除table中的数据的时候,往往是先获取table中每一行数据的id,然后将id传到后台,最后在数据库中删除,下面以删除学生为例。

jsp代码

<form action="deletestu.action" method="post"> <input type="submit" value="批量删除"/> <table width="100%" border=1>  <tr>    <td>选择</td>    <td>姓名 </td>    <td>年龄</td>    <td>出生日期</td>    <td>操作</td>  </tr> <c:forEach items="${list}" var="stu">    <tr>     <td><input type="checkbox" name="deleteid" value="${stu.id }"/></td>    <td>${stu.name } </td>    <td>${stu.age } </td>    <td><fmt:formatDate value="${stu.birthday }" pattern="yyyy-MM-dd"/> </td>    <td><a href="editstudent/${stu.id}.action">修改</a></td>  </tr> </c:forEach></table></form>

Handler接收ids数组

@RequestMapping("/deletestu")public String deleteStu(String [] deleteid) throws Exception{    System.out.println(deleteid);    return "success";}

2、List绑定

定义vo对象

public class StudentScore {    private String coursename;    private Float score;    public String getCoursename() {        return coursename;    }    public void setCoursename(String coursename) {        this.coursename = coursename;    }    public Float getScore() {        return score;    }    public void setScore(Float score) {        this.score = score;    }}public class UserVo {    //学生成绩 信息    private List<StudentScore> scores;    public List<StudentScore> getScores() {        return scores;    }    public void setScores(List<StudentScore> scores) {        this.scores = scores;    }}

jsp代码

<form action="${pageContext.request.contextPath}/stu/saveStudentList.action" method="post">    课程名:<input type="text"name="scores[0].coursename"/>成绩:<input type="text"name="scores[0].score"/><br/>    课程名:<input type="text"name="scores[1].coursename"/>成绩:<input type="text"name="scores[1].score"/><br/>    课程名:<input type="text"name="scores[2].coursename"/>成绩:<input type="text"name="scores[2].score"/><br/>    <input type="submit" value="提交 "/> </form>

Handler代码(用List接收)

@RequestMapping("/saveStudentList")public String saveStudentList(UserVo userVo) throws Exception{    System.out.println(userVo);    return "success";}
  • 先定义一个StudentScore对象,设置两个属性,score和coursename,然后再定义一个vo对象UserVo,这个对象中定义一个List<StudentScore> scores,其名字一定要和Jsp中的scores[0].coursename的scores对应,StudentCourse中的coursename和Jsp中的scores[0].coursename对应,这样才能正确的将jsp中的数据传入Handler中。

小结

以上便是小编总结SpringMvc传递参数的基础知识,下一篇博客小编介绍

1 0
原创粉丝点击