In this post, you will learn how to use the <c:url> tag in the JSTL core tags library.

You know, the <c:url> tag creates a URL and optionally stores the URL in a variable. We can use <c:param> to supply request parameters and values optionally.

 

JSTL <c:url> Syntax:

<c:url

  var="<string>"

  scope="<string>"

  value="<string>"

  context="<string>"/>

 

Attributes:

Name

Required

Type

Description

var

False

java.lang.String

The name of the variable to store the resulted URL.

scope

False

java.lang.String

The scope in which the resulted URL to be placed.

value

False

java.lang.String

URL string to be used.

context

False

java.lang.String

Name of the web application context when referencing external resources with relative path.

 

JSTL <c:url> Example:

The below example creates a URL to a resource.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
     "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>&lt;c:url&gt; Demo</title>
    </head>
    <body>
        <h1>&lt;c:url&gt; Demo</h1>
        <a href="/<c:url value="http://www.codejava.net"/>">
          This is a URL formed by &lt;c:url&gt; tag.
        </a>
     </body>
</html>

We can supply request parameters optionally to the URL as shown below.

<c:url value="/getItemDetails.jsp" var="itemDetailsURL">
   <c:param name="itemId" value="I1980X"/>
</c:url>
<a href="/<c:out value="${itemDetailsURL}"/>">Click to get item details</a>

 

Output:

url-demo

 

Recommended Usage of JSTL <c:url> tag:

Useful to create URL string and needs to store the URL in any scope for later use. Optionally we can send parameters using the tag <c:param>.

 

Other JSTL Core Tags:

if |  catch  |  choose   |  forEach  |  forTokens   |  import   |  out   |  param  |  redirect  |  remove   |  set


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#2Nam2020-06-27 16:59
Hi Michel,
I have a series of Spring tutorials here: www.codejava.net/spring-tutorials
Quote
#1michel2020-06-27 15:39
pretty cool!!!!! make some spring material too
Quote