lisak lisak - 4 months ago 53
Java Question

How to concatenate string literals inside of JSP expression within custom jsp tag

I have a really strange problem, following attribute of a jsp tag

<custom:tag onclick="addBid('<%= container_index + "string" %>');" />


cannot be processed by jsp compiler

20:18:00,374 ERROR [render_portlet_jsp:154] org.apache.jasper.JasperException: /WEB-INF/jsp/customers/abcd.jsp(146,107) equal symbol expected
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)


Simply if there are double quotes around
" '<%= %>' "
, they cannot be again inside
" '<%= " " %>' "


On the other hand, if it was in a html element :

<input id="bid" onclick="addBid('<%= container_index + "string" %>');" />


It works fine

Please don't tell me that I should use tag libraries for that... :-)

Answer

First of all in a JSP the

<%=varName%> 

scriptlet means: change the line a) with

varName.toString()

So it is strange that You want to output a variable whos name is not known.

It is like in Java You would write

String aVariableString = "test String";
System.out.println(aVariable+"String");

This has no sense.

However I can imagine a similar code to Yours depending on situation:

If just once appears, I would do in the following way:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!-- head, or anything You want -->
<script>
    function addBid(){
        var bidId = document.getElementById("bidId").value;
        // do whatever with bidId
    }
</script>

<input type="hidden" id="bidId" value="<c:out value=${containerIndexes[knownIndex]}" />    

<custom:tag onclick="addBid();" />

Of course usually we need theese data in a loop, so code changes:

<c:forEach var="bid" items="${bids}">
    <c:out value=${bid.name} /> <custom:tag onclick="addBid(${bid.index});" />
</c:foreach>

and the iterable with name bids contains objects of type bid which at least has the

getName() 

and

getIndex() 

methods.

If You want to append in JSP a custom string, then should work the

<custom:tag onclick="addBid('${bid.index} whatever string you want here');" />

If we assume an index of 12, this outputs something like:

<whateverCustomTagDoes onClick="addBid('12 whatever string you want here') />

If You still want to use scriptlet (which is not recommended in JSP) with Your example and in fact the intention was to append a string to an existing value (not building variable on the fly -like JavaScript eval-) then an answer could be:

<custom:tag onclick="addBid('<%=container_index%>string');" />