![](/img/trans.png)
[英]Set session variable using JSTL and accessing it in servlet/controller class
[英]Access jstl variable in servlet
我通過在jsp中迭代客戶列表來填充客戶數據。
<form action="CustomerUpdate" method="post">
<c:forEach var="listItems" items="${customers}">
<label> First Name: </label><c:out value="${listItems.fname}" />
<label> Last Name: </label><c:out value="${listItems.lname}" />
<label> Address: </label><c:out value="${listItems.address}" />
<input type="submit" value="Edit" name="edit">
<input type="submit" value="Delete" name="delete"><br />
</c:forEach>
</form>
現在,在操作中編輯或刪除我想要跟蹤哪個客戶需要編輯/刪除的每條記錄。 所以在servlet中我如何訪問var listItems中的customer對象。 如果不可能,我需要隱藏帶有值的輸入變量並使用servlet中的getParameter訪問它們嗎?
這只是一個如何做的簡單示例。 以這種方式更改您的代碼:
<c:forEach var="listItems" items="${customers}">
<form action="CustomerUpdate" method="post">
<input type="hidden" value="${listItems.id}" name="id">
<label> First Name: </label><c:out value="${listItems.fname}" />
<label> Last Name: </label><c:out value="${listItems.lname}" />
<label> Address: </label><c:out value="${listItems.address}" />
<input type="submit" value="Edit" name="action">
<input type="submit" value="Delete" name="action"><br />
</form>
</c:forEach>
更新
為每一行創建一個表單元素,並為每一行添加一個帶有id
的隱藏字段。 因此,當您按下該按鈕時,您將在請求中收到一個值,使您能夠檢測到該行。 通過這種方式:
String id = request.getParameter("id");
String action = request.getParameter("action");
現在你知道了id
和action
類型(編輯或刪除)。
替代方案
請勿使用表單並提交以致電您的操作,但請使用直接鏈接。
<c:forEach var="listItems" items="${customers}">
<input type="hidden" value="" name="id">
<label> First Name: </label><c:out value="${listItems.fname}" />
<label> Last Name: </label><c:out value="${listItems.lname}" />
<label> Address: </label><c:out value="${listItems.address}" />
<button onclick="window.location.href='CustomerUpdate?action=edit&id=${listItems.id}'">Edit</button>
<button onclick="window.location.href='CustomerUpdate?action=delete&id=${listItems.id}'">Delete</button>
</c:forEach>
在servlet中檢查單擊了哪個按鈕:
if (request.getParameter("action") != null) //if action is not null
{
String action = request.getParameter("action");
String id = request.getParameter("id");
if (action.equals("edit")) //edit button clicked
{
//do your work here
}
else if (action.equals("delete")) //delete button clicked
{
//your work here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.