开发者

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

开发者 https://www.devze.com 2023-03-27 10:52 出处:网络
I am trying to have a JavaScript function called when I click a link. This JavaScript function is definied in an attribute of a JSP tag and I am trying to pass a scriptlet variable to the function. Ho

I am trying to have a JavaScript function called when I click a link. This JavaScript function is definied in an attribute of a JSP tag and I am trying to pass a scriptlet variable to the function. However, it doesn't get evaluated. The relevant part of the code is:

<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 mentions a JavaScript error in the 开发者_开发百科bottom left corner. When I right click and view source, the generated HTML is:

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

So, the <%=commentUUID%> is not been evaluated in the actionOnClick attribute, but it's successfully been evaluated in id attribute.

How is this caused and how can I fix it?


I'm not sure whether the <mysecurity:secure_link> is a custom or an existing 3rd party JSP tag library. Modern JSP tags usually do not evaluate legacy scriptlet expressions. You should rather be using EL (Expression Language) instead.

First ensure that commentUUID variable is been stored as an attribute of the page or request scope so that it's available to EL, like as the following example in a preprocessing servlet:

request.setAttribute("commentUUID", commentUUID);

or using another scriptlet in JSP:

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

or using JSTL's <c:set> in JSP:

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

then you can access it as follows in EL:

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


What finally worked for me, with the @BalusC 's advice was to use editcomment(this.id.split('_')[1]). The correct working code is as follows:

<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消