springMVC 自動將form 提交對象型數據轉爲Object對象數據

*注意事項:1.我的後臺controller 層使用的是spring boot 中集成的spring mvc來獲取form表單的數據。

      2.我的前端用的是html 加thymeleaf,後面的有個地方注意一下,th:action="@{/role/test}"是thymeleaf 的標籤,主要是計算項目路徑.

1.html頁面

<span style="white-space:pre">		</span><form th:action="@{/role/test}" method="post">
			<input name="Test[0].name" value="cyc"/>
			<input name="Test[0].id" value="1"/>
			<input name="Test[1].name" value="cyc"/>
			<input name="Test[1].id" value="2"/>
			<input type="submit" value="ok"/>
		</form>

2.controller層

<span style="white-space:pre">	</span>@RequestMapping(value = "test",method=RequestMethod.POST)
	@ResponseBody
	public void test(Tests tests){
		
		System.out.println("ok");
	}
3.Tests 封裝的對象

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爲接受頁面傳來的對象

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:

我才發現一個問題那就是

<form th:action="@{/role/test}" method="post">
	<input name="Test[0].name" value="cyc"/>
	<input name="Test[0].id" value="1"/>
	<input name="Test[<span style="color:#ff0000;">2</span>].name" value="cyc"/>
	<input name="Test[<span style="color:#ff0000;">2</span>].id" value="2"/>
	<input type="submit" value="ok"/>
</form>
這時後臺接收到的對象有三個下表爲1的所有屬性都爲null

如果這樣寫的話會創建3個對象。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章