Question

I am using JSP and Spring framework. In a page, I want to have five buttons next to a corresponding select element. My question is how can I avoid repeating the code for that?

Here is the code I have for one button-select combination:

       <tr>
            <td>
                <sf:label path="inputFile">Select a file:</sf:label>
            </td>
            <td>
                <sf:select path="inputFile" cssStyle="width: 250px;" onchange="enableLocal(this.selectedIndex,'matButton')">
                    <sf:option value="Upload a Local File" />
                    <sf:option value=" --- Available already: --- " disabled="true" />
                    <sf:options items="${flowData.availableInputs}" />
                </sf:select>
            </td>
            <td>
                <input id="matButton" type="file" name="inputFile"/>
            </td>
        </tr>

In the above code, the names inputFile and matButton are to be treated as parameters, i.e., other buttons will have different names.

What I have in mind is something like a function with the two parameters that would generate the above code. Is it possible?

Was it helpful?

Solution

Create a custom JSP tag file.

/WEB-INF/tags/file.tag

<%@ tag body-content="empty" %>
<%@ attribute name="selectPath" required="true" type="java.lang.String" %>
<%@ attribute name="buttonId" required="true" type="java.lang.String" %>
<%@ taglib prefix="sf" uri="...???..." %>

<tr>
    <td>
        <sf:label path="${selectPath}">Select a file:</sf:label>
    </td>
    <td>
        <sf:select path="${selectPath}" cssStyle="width: 250px;" onchange="enableLocal(this.selectedIndex,'${buttonId}')">
            <sf:option value="Upload a Local File" />
            <sf:option value=" --- Available already: --- " disabled="true" />
            <sf:options items="${flowData.availableInputs}" />
        </sf:select>
    </td>
    <td>
        <input id="${buttonId}" type="file" name="inputFile"/>
    </td>
</tr>

(I have no idea what that sf taglib is, you've to complete its URI yourself)

Use it as follows where file is the base filename of the .tag file:

<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
...
<my:file selectPath="inputFile" buttonId="matButton" />

OTHER TIPS

As written above, you can use custom tag jsp. Then, you can declare somewhere in a model all pairs (inputFile & matButton) you want to use, and use core tag libs (<c:forEach>). Refer to this example. This will iterate over your collection which contains label definitions (all these actions you can make from a controller).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top