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

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.


Here is a short snippet from my training app where I use <c:url> tag:

<table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Action</th>
    </tr>
    
    <c:forEach var="student" items="${student_list}">
    
        <c:url var="loadStudentLink" value="StudentControllerServlet">
            <c:param name="command" value="load"/>
            <c:param name="id" value="${student.id}"/>
        </c:url>
    
        <tr>
            <td> ${student.firstName} </td>
            <td> ${student.lastName} </td>
            <td> ${student.email} </td>
            <td> 
                <a href="${loadStudentLink}">Update</a>
            </td>
        </tr>   

    </c:forEach>                
</table>

Of course in this case I could just use the link below and it would be the same:

<a href="StudentControllerServlet?command=load&id=${student.id}">Update</a>

In a nutshell, <c:url> creates an ordinary link which you can store in a variable and define its scope. With <c:param> tags you can set parameters for the link. In addition, some could say that it looks more neatly with JSTL.

Also, as it was said before, <c:url> already has context path of the app. So, for instance, you can do this

<link rel="stylesheet" href="<c:url value="/resources/css/test.css"/>" />

instead of that

<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/test.css" />

Tags:

Java

Jstl