20 - JSP Standard Tag Library (JSTL): Page 6 of 7

20.3.11 <c:url>

The <c:url> tag is used to create a URL with optional query string. This tag also allows to store the generated url in a variable and does the URL rewriting automatically whenever required.

<c:url var=”variable_name” value=”relative_url" context=”/ another web application context root” />

· value- is the mandatory attribute and it specifies the value of Url.

· context- is an optional attribute and it can have value of context of another web application running on same server prepend with / . This is useful if we need to redirect to page of another web application running on same server.

var- variable which can be used to store the generated url

Note: In URL tags, when the "context" attribute is specified, values of both "context" and "value" must start with "/"

Example-

Let's create curl.jsp which will create two links

a) link to open Google.com

b) link to open login.jsp of HelloWorld web application created in section 20.3.3

<html>
  <head>
    <title> c url tag Example </title>
  </head>
  <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
  <body>
    <c:urlvar="googleUrl" value="http://www.google.com" />
    <a href="${googleUrl}">Google</a>
    <br/>
    <c:urlvar="loginUrl" value="/login.jsp" context="/HelloWorld"></c:url>
    <a href="${loginUrl}">Login</a>
  </body>
</html>

Access curl.jsp by hitting http://localhost:8080/jsp-tutorial/curl.jsp.

Click on Google link you will see google.com

Access curl.jsp by hitting http://localhost:8080/jsp-tutorial/curl.jsp and click on Login link

20.3.12 <c:param>

This tag is mostly used with <c:url> and <c:redirect> tags. Basically it adds parameter and their values to the output of these tags.

This tag has two attributes –

a)name name of variable

b)value value of variable

<c:param name=”param-name” value=”param-value” />

Parameters added as <c:param> tag gets added as query parameters

Example-

Lets create cparam.jsp which will create one link to Google using <c:url> tag and will add one param with name “q” and value “jsp”

<html>
  <head>
    <title> c param tag Example </title>
  </head>
  <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
  <body>
    <c:urlvar="googleUrl" value="http://www.google.com">
    <c:param name="q" value="jsp"></c:param>
    </c:url>
    <a href="${googleUrl}">Google</a>
    <br/>
  </body>
</html>

Access cparam.jsp by hitting http://localhost:8080/jsp-tutorial/cparam.jsp and click on Google link

Similarly we can use it with <c:redirect> tag as well.

 

Like us on Facebook