我像https://stackoverflow.com/a/207882/242042一样实现它并封装了https://stackoverflow.com/a/775295/242042以便它可以作为标签重复使用。
<%@ tag
display-name="element"
pageEncoding="utf-8"
description="similar to jsp:element with the capability of removing attributes that are blank, additional features depending on the key are documented in the tag."
trimDirectiveWhitespaces="true"
dynamic-attributes="attrs"
%>
<%@ attribute
name="tag"
description="Element tag name. Used in place of `name` which is a common attribute in HTML"
required="true"
%>
<%-- key ends with Key, use i18n --%>
<%-- key starts with x-bool- and value is true, add the key attribute, no value --%>
<%-- key starts with x-nc- for no check and value is empty, add the key attribute, no value --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<jsp:text><![CDATA[<]]></jsp:text>
<c:out value="${tag} " />
<c:forEach var="attr" begin="0" items="${attrs}">
<c:choose>
<c:when test='${fn:endsWith(attr.key, "Key")}'>
${attr.key}=<fmt:message key="${attr.value}" />
</c:when>
<c:when test='${fn:startsWith(attr.key, "x-bool-") && attr.value == "true"}'>
<c:out value="${fn:substringAfter(attr.key, 'x-bool-')}" />
</c:when>
<c:when test='${fn:startsWith(attr.key, "x-bool-") && attr.value != "true"}'>
</c:when>
<c:when test='${fn:startsWith(attr.key, "x-nc-")}'>
<c:out value="${fn:substringAfter(attr.key, 'x-nc-')}" />="<c:out value='${attr.value}' />"
</c:when>
<c:when test='${not empty attr.value}'>
<c:out value="${attr.key}" />="<c:out value='${attr.value}' />"
</c:when>
</c:choose>
<c:out value=" " />
</c:forEach>
<jsp:doBody var="bodyText" />
<c:choose>
<c:when test="${not empty fn:trim(bodyText)}">
<jsp:text><![CDATA[>]]></jsp:text>
${bodyText}
<jsp:text><![CDATA[<]]></jsp:text>
<c:out value="/${tag}" />
<jsp:text><![CDATA[>]]></jsp:text>
</c:when>
<c:otherwise>
<jsp:text><![CDATA[/>]]></jsp:text>
</c:otherwise>
</c:choose>
要使用它,请将其放在 taglib tagdir 中。
<%@ taglib tagdir="/WEB-INF/tags" prefix="xyz"%>
...
<xyz:element tag="input"
type="date"
id="myDate"
name="myDate"
x-bool-required="true"
/>
输出将呈现为
<input
name="myDate"
id="myDate"
type="date"
required/>