如何在jstl代码中混合href [英] How to mix href within jstl code
问题描述
当我使用下面的jstl代码
When I use the below jstl code
<a href="http://mysite.com?id="<c:out value="${myid}"/>/><c:out value="${myid}"/></a>
输出为:
"1234"
值1234对应于myid的变量值,但所生成的url为 " http://mysite.com?id= ",因此myid的值不会作为href.
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.
如何修改href,以便显示整个href:
How can I amend the href so that entire href is displayed :
而不是:
推荐答案
最终,JSP/JSTL生成HTML.您熟悉基本HTML ,对吗?
Ultimately, JSP/JSTL generates HTML. You're familiar with basic HTML, right?
通过右键单击浏览器中的查看源代码,更仔细地查看生成的HTML输出.您会看到:
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>
有效 HTML吗?不,您在错误的位置使用"
关闭属性值太早,而使用/>
则关闭标签太早.看起来,Stack Overflow HTML语法荧光笔也感到困惑.相反,它应该是:
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>
相应地修复HTML生成器(即JSP/JSTL代码),以便生成所需的HTML:
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>
但是如果不能保证${myid}
是数字(因为它是String
),则应该使用<c:url>
和<c:param>
正确地
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>
这篇关于如何在jstl代码中混合href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!