对于这个<select><option selected="selected">
问题,我决定我不会介意有点冗长,如果它只是一次性冗长......所以我创建了一个标签文档(.tagx),/WEB-INF/tags/select.tagx
如下所示:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:directive.attribute name="id" required="true" />
<jsp:directive.attribute name="name" required="true" />
<jsp:directive.attribute name="options" required="true" />
<jsp:directive.attribute name="selected" required="true" />
<select id="${id}" name="${name}">
<c:forEach var="opt" items="${options}">
<c:choose>
<c:when test="${opt == selected}"><option selected="selected">${opt}</option></c:when>
<c:otherwise><option>${opt}</option></c:otherwise>
</c:choose>
</c:forEach>
</select>
</jsp:root>
并像这样使用它:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<html xmlns="http://www.w3.org/1999/xhtml" version="2.1"
...
xmlns:form="urn:jsptagdir:/WEB-INF/tags/">
...
<head>
...
</head>
<body>
<form method="POST" commandName="loginRequest" action="index_login.html">
<fieldset id="loginFieldSet">
...
<div>
<label for="day" path="day">Favourite day: </label>
<form:select id="day" name="day" selected="Saturday"
options="Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday" />
</div>
</fieldset>
<div>
<input type="submit" tabindex="3" />
<input type="reset" tabindex="4" />
</div>
</form>
</body>
</html>
krosenvold,我不同意这很丑……也许很烦人,但我很高兴我不必为此编写任何代码。一旦定义了标记,您的 JSPX 就会变得更加整洁。此外,我根本不认为这有捷径。