简体   繁体   中英

Is there a better way to write this JSP custom tag?

I'm creating a JSP .tag file that will handle this use case:

<my:safeParam paramName="param1" defaultValue="testvalue"/>

Where the behavior will be to take a request parameter, escape its value for "safe" usage, and place that escaped value back on some scope (eg request) under the same name as the parameter (although it could be another name).

I have an implementation that works, but I've got scriptlet in there because I couldn't find a way to use variable variable names in just JSTL. But I'm no JSTL wizard, so I thought I'd see if there's a syntax/approach I'm missing. Here's the working safeParam.tag file:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<%@ attribute name="paramName" required="true" %>
<%@ attribute name="defaultValue" %>

<%
    String name = (String) pageContext.getAttribute("paramName");
%>

<c:if test="${not empty defaultValue}">
<%
    request.setAttribute(name, pageContext.getAttribute("defaultValue"));
%>
</c:if>

<c:if test="${not empty param[paramName]}">
    <c:set var="escaped" value="${fn:escapeXml(param[paramName])}"/>
<%
    request.setAttribute(name, pageContext.getAttribute("escaped"));
%>
</c:if>

(I sure wish EL was escaped automatically.)

<c:if test="${empty paramName}">
    ${defaultValue}
</c:if>
<c:if test="${not empty paramName}">
    <c:out value="${paramName}" escapeXml="true"/>
</c:if>

I probably won't use this approach because it reduces the conciseness I was seeking with this custom tag, but just to document it as an option... (I'm not sure if this is what Frank Yeung is getting at.)

I could make the tag simply output the default-or-escaped parameter value, then make the user of the tag wrap that in a <c:set> .

Tag:

<c:choose>
<c:when test="${empty param[paramName]}">
    ${defaultValue}
</c:when>
<c:otherwise>
    <c:out value="${param[paramName]}"/>
</c:otherwise>
</c:choose>

JSP:

<c:set var="myVariable">
    <my:safeParam paramName="folder" defaultValue="homeFolder"/>
</c:set>

But really my goal has been to do everything inside the tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM