简体   繁体   中英

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>

Referring to the above code, I am getting session object projDetails from some servlet, and displaying its contents in a JSP. Since arraylist projDetails have more than one records the field pID also assumes different value, and the display will be a table with many rows.
Now I want to call a servlet showProj when the user clicks on "View Team" (which will be in each row) based on the that row's "pID". Could someone please let me know how to pass the particular pID which the user clicks on JSP to servlet?

Instead of an <input> for each different pID, you could use links to pass the pID as a query string to the servlet, something like:

<a href="/showProj?pID=${it.pID}">View Team</a>

In the showProj servlet code, you'll access the query string via the request object inside a doGet method, something like:

public void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException
{
    String pID = request.getParameter("pID");
    //more code...
}

Here are some references for Java servlets:

HttpServletRequest object
Servlet tutorials

Pass the pID along in a hidden input field.

<td>
    <form action="showProj">
        <input type="hidden" name="pID" value="${it.pID}">
        <input type="submit" value="View Team">
    </form>
</td>

(please note that I rearranged the <form> with the <td> to make it valid HTML and I also removed the id from the button as it's invalid in HTML to have multiple elements with the same id )

This way you can get it in the servlet as follows:

String pID = request.getParameter("pID");
// ...

Define onclick function on the button and pass the parameter

<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>
.....

Define javascript function:

function populatePid(name) {
  document.getElementById('pId') = name;
}

and in the servlet:

public void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException
{
    String pID = request.getParameter("pId");
    .......
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM