Search code examples
javajstl

What is the purpose of jstl's c:url tag?


TutorialPoint has a simple example of the c:url tag that looks like this:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:url> Tag Example</title>
</head>
<body>
<a href="<c:url value="/jsp/index.htm"/>">TEST</a>
</body>
</html>

When looking at the corresponding rendering with Chrome's developer tooling it renders like this:

<a href="/jsp/index.htm">TEST</a>

So the c:url tag seems redundant, but I'm sure I'm missing something?


Solution

  • As Tutorials Points says, It is for formatting purposes of the URL you put in and it can be stored in a variable.

    Example you have this:

    <a href="<c:url value="/test.html"/>">TEST</a>
    

    if you click TEST, it will go to page test.html. simple as that. but the question is, what is the value of <c:url value="/test.html"/> ?

    are you thinking the value is only /test.html?

    try to test it, like this:

    <a href="<c:url value="/test.html" var="testvar" />">TEST</a> // testvar is where you put the url formatted by c:url
    <c:out value="${testvar}"/> // you print what is the formatted url
    

    the answer will be the Context Folder of your project plus the URL you put in.

    context/test.html will be the output.

    I think that its purpose is to have the context (Current Application) already given to the URL, and you only need to add the remaining URL part.