Search code examples
javajspstruts2ognlstruts-tags

How to send data from JSP to Action with <s:a> in Struts2?


I want to achieve that clicking the title, the matching id is sent to the Action, but id in the Action is always zero.

The Action uses the id to search the matching record in database and show in another jsp.

<s:iterator id="n" value="news">
<tr>
    <td>
    <s:url action="GETNEWS" var="getNews">
        <s:a href="%{getNews}">
            <s:property value="#n.title" />
            <s:hidden name="id" value="#n.id" />
        </s:a>
    </s:url>
    </td>
</tr>
</s:iterator>

Solution

  • id in <s:iterator> is deprecated (unless you are using an aeon-old version). Use var instead.

    Use <s:param> inside <s:url> (and, for a better coding, remember to specify the namespace).
    Then reference the <s:url> from <s:a>.

    Finally, ensure you have the right Setter in your action.

    <s:iterator var="n" value="news">
    <tr>
        <td>
    
            <s:url action="GETNEWS" namespace="/" var="getNews">
                <s:param name="id">
                    <s:property value="#n.id" />
                </s:param>
            </s:url>
    
            <s:a href="%{getNews}">
                <s:property value="#n.title" />
            </s:a>
    
        </td>
    </tr>
    </s:iterator>