[英]How do i pass an object from jsp to controller with spring
我有一個User類,一個Project類具有與用戶的arraylist。 我有一個包含所有我的項目列表的“項目”頁面,當我單擊一個項目頁面時,通過在url中發送該項目的ID將其帶到該項目的頁面。
在我的詳細項目頁面上,我想添加我創建的用戶。 用戶顯示在表格中的模態上,並帶有一個添加按鈕。
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<h1 class="text-center">UserList</h1>
<br><br>
<table class="table table-hover">
<thead>
<tr>
<th>Photo</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Function</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<c:forEach var="u" items="${users}">
<tr>
<td><img src="${u.getPhoto()}"
alt="Alternate Text" class="img-responsive" /></td>
<td>${u.getFirstname()}</td>
<td>${u.getLastname()}</td>
<td>${u.getFunction()}</td>
<td>${u.getEmail()}</td>
<td><Button type="Button" class="btn btn-default">Add</button></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
我的問題是如何發送用戶ID和我希望他們添加到控制器的項目ID?
我知道我可以使用網址傳遞ID,但是我不想打開新頁面。
我想通過單擊控制器上的添加按鈕將用戶和項目的ID發送到控制器,以便可以在名為addUserToProject()的方法中使用這些ID
在呈現的頁面上,您只有兩個選項,要么進行常規表單發布,要么如果不想打開新的URL,請使用Ajax。
JSP
首先,使用選定的項目ID進行隱藏輸入,以便稍后獲取:
<input type="hidden" id="currentProjectId" value="12">
其次,將添加按鈕的屬性名稱設置為等於userId :
<td><Button type="Button" name="${u.getId()}" class="btn btn-default">Add</button></td>
Javascript:
為每個“添加按鈕”定義onclick linstener並從該按鈕獲取當前用戶ID:
$(".btn").click(function(event) {
event.preventDefault();
var currentProjectId= $('#currentProjectId').val();
var userId = $(this).attr("name");
addUser(currentProjectId, userId);
});
發出ajax請求並將ID發布到控制器:
function addUser(currentProjectId, selectedUserId) {
$.ajax({
type : "POST",
contentType : "application/json",
url : "/addUserToProject",
data :{ projectId: currentProjectId, userId: selectedUserId},
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
最后,控制器使用@RequestParam接受ID :
@RequestMapping(value = "/addUserToProject", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
String Submit(@RequestParam("projectId") Integer projectId ,@RequestParam("userId ") Integer userId ) {
//insert user
return "ok";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.