Search code examples
javahtmlsqljsp

How to get value from select and put to another select in JSP


I have two select tags with sql query in one jsp page. How to put value from select 1 to the second select?

From

<sql:query var="priv_query">
    SELECT priv_id from en_privilegetypes
    where actual = 1
</sql:query>

To

<sql:query var="itemquery">
    SELECT ItemName  from en_items
    where actual = <!-- priv_id  value from priv_query -->
</sql:query>

Solution

  • You can use JSTL:

    <!-- List of priv_id values -->
    <c:set var="priv_id_list" value="" />
    
    <!-- Loop through and append the values to the list -->
    <c:forEach items="${priv_query.rows}" var="row">
        <c:set var="priv_id_list" value="${priv_id_list}${row.priv_id}" />
        <c:if test="${!loop.last}">,</c:if>
    </c:forEach>
    
    <sql:query var="itemquery">
        SELECT ItemName from en_items
        where actual IN (${priv_id_list})
    </sql:query>
    

    The <c:forEach> iterates the result set of the first query and append each priv_id value to priv_id_list.

    And then you can use the IN clause with ${priv_id_list} to your second query.