Scriptlet变量不会在自定义JSP标记的属性中求值

Scriptlet variable doesn't get evaluated inside an attribute of a custom JSP tag

本文关键字:属性 JSP 变量 自定义 Scriptlet      更新时间:2023-09-26

我试图有一个JavaScript函数调用时,我点击一个链接。这个JavaScript函数是在JSP标记的属性中定义的,我试图将scriptlet变量传递给该函数。然而,它没有被求值。代码的相关部分是:

<span>
  <mysecurity:secure_link id='<%="editButton_"+commentUUID%>' entitlement="" 
    actionOnClick="editComment('<%= commentUUID %>');return false;"
    isSurroundedByBrackets="true" enableTitle="" disableLink="<%=disableLink%>">
    <span style="color:#0033BB; font:8pt arial;">
      <bean:message key="button.edit" />
    </span>
   </mysecurity:secure_link>
</span>

IE8在左下角提到一个JavaScript错误。当我右键单击并查看源代码时,生成的HTML是:

onclick="editComment('<%= commentUUID %>');return false;"

因此,<%=commentUUID%>actionOnClick属性中没有被求值,而在id属性中被求值成功。

这是如何引起的,我如何解决它?

我不确定<mysecurity:secure_link>是自定义的还是现有的第三方JSP标记库。现代JSP标记通常不计算遗留的scriptlet表达式。你应该使用EL(表达式语言)来代替。

首先确保commentUUID变量被存储为页面或请求作用域的属性,以便它对EL可用,如下面的预处理servlet示例所示:

request.setAttribute("commentUUID", commentUUID);

在JSP中使用另一个脚本:

<% request.setAttribute("commentUUID", commentUUID); %>

使用JSTL的<c:set>在JSP:

<c:set var="commentUUID"><%=commentUUID%></c:set>

,那么您可以在EL中按如下方式访问它:

<mysecurity:secure_link actionOnClick="editComment('${commentUUID}');return false;" />

最后对我有用的是,使用@BalusC的建议是使用editcomment(this.id.split('_')[1])。正确的工作代码如下:

<span>
  <mysecurity:secure_link id='<%="editButton_"+commentUUID%>' entitlement="" 
      actionOnClick="javascript:editComment(this.id.split('_')[1]);return false;"
      isSurroundedByBrackets="true" enableTitle="" disableLink="<%=disableLink%>">
      <span style="color:#0033BB; font:8pt arial;">
         <bean:message key="button.edit" />
      </span>
  </mysecurity:secure_link>
</span>