[英]How to pass a session value as request parameter from JSP to servlet?
<c:forEach var="it" items="${sessionScope.projDetails}">
<tr>
<td>${it.pname}</td>
<td>${it.pID}</td>
<td>${it.fdate}</td>
<td>${it.tdate}</td>
<td> <a href="${it.address}" target="_blank">Related Documents</a></td>
<td>${it.pdesc}</td>
<form name="myForm" action="showProj">
<td><input id="button" type="submit" name="${it.pID}" value="View Team">
</td>
</form>
</c:forEach>
參考上面的代碼,我從一些servlet獲取會話對象projDetails
,並在JSP中顯示其內容。 由於arraylist projDetails
具有多個記錄,因此字段pID
也會采用不同的值,並且顯示內容將是一個包含許多行的表。
現在,我想在用戶基於該行的“ pID”單擊“查看團隊”(將在每一行中)時調用servlet showProj
。 有人可以讓我知道如何將用戶單擊JSP的特定pID
傳遞給servlet嗎?
您可以使用鏈接將pID作為查詢字符串傳遞給servlet,而不是為每個不同的pID使用<input>
,例如:
<a href="/showProj?pID=${it.pID}">View Team</a>
在showProj
Servlet代碼中,您將通過doGet
方法內的request
對象訪問查詢字符串,如下所示:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pID");
//more code...
}
以下是Java Servlet的一些參考:
在隱藏的輸入字段中傳遞pID
。
<td>
<form action="showProj">
<input type="hidden" name="pID" value="${it.pID}">
<input type="submit" value="View Team">
</form>
</td>
(請注意,我用<td>
重新排列了<form>
以使其成為有效的HTML,並且還從按鈕中刪除了id
,因為它在HTML中無效,因為它具有多個具有相同id
元素)
這樣,您可以在servlet中獲取它,如下所示:
String pID = request.getParameter("pID");
// ...
在按鈕上定義onclick函數並傳遞參數
<form name="myForm" action="showProj">
<input type='hidden' id='pId' name='pId'>
<td><input id="button" type="submit" name="${it.pID}" value="View Team" onclick="populatePid(this.name)">
</td>
.....
定義javascript函數:
function populatePid(name) {
document.getElementById('pId') = name;
}
並在servlet中:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pId");
.......
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.