Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix href within jstl code

Tags:

jstl

When I use the below jstl code

  <a href="http://mysite.com?id="<c:out value="${myid}"/>/><c:out value="${myid}"/></a> 

the output is :

"1234"

The value 1234 corresponds to the variable value of myid but the url being generated is "http://mysite.com?id=" so no value for myid is being generated as part of the href.

How can I amend the href so that entire href is displayed :

"http://mysite.com?id=1234"

instead of :

"http://mysite.com?id="

like image 618
blue-sky Avatar asked Nov 28 '22 02:11

blue-sky


1 Answers

Ultimately, JSP/JSTL generates HTML. You're familiar with basic HTML, right?

Look closer at the generated HTML output by rightclick, View Source in browser. You'll see:

<a href="http://mysite.com?id="1234/>1234</a> 

Is that valid HTML? No, you're closing the attribute value too soon with " at wrong place and you're closing the tag too soon with />. Look, the Stack Overflow HTML syntax highlighter also got confused. Instead, it should have been:

<a href="http://mysite.com?id=1234">1234</a> 

Fix the HTML generator (i.e. the JSP/JSTL code) accordingly so that it generates the desired HTML:

<a href="http://mysite.com?id=<c:out value="${myid}"/>"><c:out value="${myid}"/></a> 

Unrelated to the concrete problem, the <c:out> is only helpful in preventing XSS attack holes when redisplaying user-controlled input and actually the wrong tool to inline URL parameters. If you can guarantee that ${myid} is always a number (because it's a Long or Integer), you can even just leave it entirely out, making the code prettier to read:

<a href="http://mysite.com?id=${myid}">${myid}</a> 

If the ${myid} is however not a guaranteed to be a number (because it's a String), then you should use <c:url> and <c:param> to properly URL-encode it:

<c:url value="http://mysite.com" var="myURL">
    <c:param name="id" value="${myid}" />
</c:url>
<a href="${myURL}"><c:out value="${myid}" /></a>
like image 192
BalusC Avatar answered Dec 09 '22 18:12

BalusC