33

Can I use <spring:url value="/something" /> inside of an <a> tag?

peterh
  • 11,875
  • 18
  • 85
  • 108
213897
  • 1,561
  • 4
  • 15
  • 16

1 Answers1

63
 <spring:url value="/something" var="url" htmlEscape="true"/>
 <a href="${url}">...</a>

But you an also use c:url

 <c:url value="/something" var="url"/>
 <a href="<c:out value='${url}'/>">...</a>

The one important difference between c:url and spring:url is, that c:url does not html encode the created url. But for a valid url the & between the url parameters must be a &amp;. So you need the c:out to escape it. -- In spring:url you have this functionality already included (if I understand the documentation correct).

Namespaces:

  • xmlns:spring="http://www.springframework.org/tags"
  • xmlns:c="http://java.sun.com/jsp/jstl/core"

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/spring.tld.html#spring.tld.url

Ralph
  • 118,862
  • 56
  • 287
  • 383
  • 3
    You can also use the c:url tag within the href attribute of the anchor tag directly, as in ... – digitaljoel Feb 15 '11 at 18:52
  • 1
    @digitaljoel: This correct -- as long as no escaping is needed -- stacking a-href c:out and c:url would cause strange (IDE/Eclipse) problems because there are only two type of apostrophe (`"` and `'`) -- (be aware of the problem that even if you do not define a parameter, c:out could add a parameter for session handling (if cookies are disabled)) – Ralph Feb 15 '11 at 19:02
  • would I need to use ` – 213897 Feb 15 '11 at 19:47
  • 1
    @213897 when using spring:url with htmlEncoding="true" then ${} is ok, else you need c:out for encoding – Ralph Feb 15 '11 at 20:09
  • @Ralph correct, I figured that was assumed since you had covered the escaping in your excellent answer. As for the quoting problem, I've seen it where the same type of quote was used and eclipse didn't complain, but that doesn't mean it's the best way to go. For simple values though, I think having it in the href attribute directly is ok. – digitaljoel Feb 15 '11 at 21:16
  • @213897 - no problem, if it helped you, feel free to accept the answer. (click the checkmark) – Ralph Feb 16 '11 at 08:13
  • Additionally, `` allows the usage of inner `` elements for setting request parameters. – Patrick Bergner Nov 14 '13 at 08:49
  • What are the namespace URLs for `c:` and `spring:` there? – rakslice May 06 '14 at 23:40
  • @rakslice: see my extended answer – Ralph May 07 '14 at 07:05
  • @marchWest: you are rigth, the correct attribute name is: `htmlEscape` - I have updated the answer - thanks – Ralph Jul 21 '14 at 20:34
  • Why use "..." when you can use ...? – borjab Feb 15 '16 at 12:57
  • 1
    @borjab: To escape the "&" character (if the url has two or more request parameters) – Ralph Feb 15 '16 at 16:10