简体   繁体   English

有没有更好的方法来编写此JSP自定义标记?

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

I'm creating a JSP .tag file that will handle this use case: 我正在创建一个处理此用例的JSP .tag文件:

<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. 我有一个可行的实现,但是我那里有scriptlet,因为我找不到仅在JSTL中使用变量变量名的方法。 But I'm no JSTL wizard, so I thought I'd see if there's a syntax/approach I'm missing. 但是我不是JSTL向导,所以我想看看是否缺少一种语法/方法。 Here's the working safeParam.tag file: 这是工作中的safeParam.tag文件:

<%@ 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.) (我希望EL自动逃脱。)

<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> . 我可以使标记简单地输出默认值或转义的参数值,然后使标记的用户将其包装在<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: 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. 但实际上,我的目标是在代码中进行所有操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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