您的位置:首页 > 移动开发 > Objective-C

springMVC 自动将form 提交对象型数据转为Object对象数据

2016-02-02 00:00 417 查看
摘要: springMVC 自动将form 提交对象型数据转为Object对象数据

注意事项:1.我的后台controller 层使用的是spring boot 中集成的spring mvc来获取form表单的数据。
2.我的前端用的是html 加thymeleaf,后面的有个地方注意一下,th:action="@{/role/test}"是thymeleaf 的标签,主要是计算项目路径.
1.html页面
[html] view plain copy
<span style="white-space:pre">        </span><form th:action="@{/role/test}" method="post">
[html] view plain copy
<input name="Test[0].name" value="cyc"/>
<input name="Test[0].id" value="1"/>
[html] view plain copy
<input name="Test[1].name" value="cyc"/>
<input name="Test[1].id" value="2"/>
[html] view plain copy
<input type="submit" value="ok"/>
lt;/form>

2.controller层
[java] view plain copy
<span style="white-space:pre">    </span>@RequestMapping(value = "test",method=RequestMethod.POST)
@ResponseBody
public void test(Tests tests){

System.out.println("ok");
}
3.Tests 封装的对象
[java] view plain copy
public class Tests implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Test> test;
public List<Test> getTest() {
return test;
}
public void setTest(List<Test> test) {
this.test = test;
}
}
4.Test为接受页面传来的对象[java] view plain copy
public class Test implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String name;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

5.注意事项:1>Test和Tests都需要实现Serializable接口,实现序列化。
2>注意页面上的写法test[0].id和test[0].name这就是对象数据。

6.ajax传对象(探索)
var map = [{name:"cyc",id:1},{name:"zwt",id:2}];
$.post("",{test:map},function(){
});
开始我以为这种方式可以用我的Tests进行数据注入,其实是不行的,在浏览器的form data 中显示 test[0][id]=1 test[0][name]=cyc test[1][id]=2 test[0][name]=zwt。
这种形式显然框架不认识这是个对象,也可以通过request.getParamter(" test[0][id]");但是这种方式不能注入数据为对象,目前有两种方法可以解决这种问题,那就是1.自己写个转换器将这种格式的转成对象,另外一种方法就是序列化数据在反序列化,但是都不是一种很简单方法,这种提交表单的方式最简单了,经过本人的测试。
谢谢大家的支持!

补充1:
我才发现一个问题那就是
[html] view plain copy
<form th:action="@{/role/test}" method="post">
[html] view plain copy
<input name="Test[0].name" value="cyc"/>
<input name="Test[0].id" value="1"/>
[html] view plain copy
<input name="Test[<span style="color:#ff0000;">2</span>].name" value="cyc"/>
<input name="Test[<span style="color:#ff0000;">2</span>].id" value="2"/>
[html] view plain copy
<input type="submit" value="ok"/>
lt;/form>
这时后台接收到的对象有三个下表为1的所有属性都为null如果这样写的话会创建3个对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息