Nearby lessons

28 of 30

JSP Examples - JSTL

📌 What You Will Learn
  • Set up JSTL in a web app
  • Use the core tag library without scriptlets
  • Iterate collections with c:forEach and c:forTokens

JSTL core library programs: installing JSTL, general-purpose tags (c:out, c:set, c:remove, c:catch), conditional tags and the iteration tags (c:forEach, c:forTokens) with loop-status demos.

Installing JSTL

Defines several API classes defined by SUN.

Example01
Loading editor…

Installing JSTL

Contains implementation classes provided by vendor.

Note:

It is recommended to place these jar files at server level.(D:\Tomcat 7.0\lib) instead of application

level.

To make core library available to JSP, we have to declare taglib directive as follows...

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Example02
Loading editor…

General Purpose Tags

<c:out>

where c is prefix and out is name of tag.

This tag can be used for writing Template text data and expressions to the JSP.

form-1:

<c:out value="durga" />

It prints durga to JSP

<c:out value="${param.user}" />

It prints the value of request parameter user to the JSP.

form-2:

If the main value is not available or it evaluates to null, then we can provide default value by using

default attribute.

<c:out value="${param.user}" default="Guest" />

test.jsp:

Example03
Loading editor…

General Purpose Tags

o/p: Hello Guest

Note:

<c:out> can accept the following 3 attributes

1.value

2.default

3.escapeXml

2.<c:set>

We can use <c:set> to set attributes in any scope and to set map and bean properties also.

Form-1:

We can use <c:set> to set attributes in any scope

<c:set var="name of the attribute" value="attributevalue" scope="request" />

scope attribute is optional and default scope is page scope.

test.jsp:

Example04
Loading editor…

General Purpose Tags

We can set map or bean properties by using <c:set>

We can specify bean or map object by using target attribute and property name by using property

attribute.

<c:set target="customer" property="name" value="pavan" />

The attributes for the <c:set> are:

1.var 2. value 3. scope 4. target 5. property

Example05
Loading editor…

General Purpose Tags

To remove attributes in the specified scope we can use this tag.

This tag can take the following 2 attributes

1.var Name of the Attribute

2.scope The Scope in which Attribute Present

Eg: <c:remove var="x" scope="session" />

If the scope is not specified then the container will search in the page scope for the required

attribute. If the attribute is not available then it will search in the request scope followed by

session and application scopes.

test.jsp:

Example06
Loading editor…

General Purpose Tags

This tag can be used to catch an exception within the JSP instead of forwarding to the error page.

The risky code we have to place as the body of <c:catch>

<c:catch >

Risky Code

</c:catch>

If an exception raised in the risky code, then this tag suppresses that exception and rest of the JSP

will be executed normally.

If an exception is raised we can hold that by using var attribute, which is the page scoped

attribute.

test.jsp:

Example07
Loading editor…

General Purpose Tags

http://localhost:7777/jsp1/catch1.jsp?uname=pavan&uage=47&uheight=5.11

User Name: pavan

Age:47

User Height: 5.11

http://localhost:7777/jsp1/catch1.jsp?uname=pavan&uage=ten&uheight=5.11

User Name: pavan

Oops ...Exception raised : java.lang.NumberFormatException: For input string: "ten"

User Height: 5.11

Summary of General Purpose Tags

TagDescriptionAttribute
1) <c:out>Value, default,
For writing ExpressionescapeXml
2) <c:set>and Template Text to JSPvar, value, scope

target, property

Example08
Loading editor…

General Purpose Tags

For removing Attributes

For supporting an Expression

and to continue rest of Jsp

normally

Conditional Tags

1.<c:if>

We can use to implement core java if statement.

There are 2 forms are available for <c:if>

without body:

<c:if test="test_condition" var="x" scope="session"/>

In this case test_condition will be evaluated & store its results into variable x. In the rest of the

page where ever this test condition is required, we can use directly its value without evaluating

once again.

In this case both test and var attributes are mandatory. scope attribute is optional and default

scope is page.

test.jsp:

Example09
Loading editor…

General Purpose Tags

If test_condition is true then body will be executed otherwise without executing body rest of the

jsp will be continued.

In this case also we can store test result inside var attribute.

Both var and scope attributes are optional but test attribute is mandatory.

test.jsp:

Example10
Loading editor…

General Purpose Tags

<c:choose>,<c:when> and <c:otherwise>:

We can use these tags for implementing if-else and switch statements.

  • Implementing if-else:

JSTL does not contain any tag for else. We can implement if-else statement by using above tags.

Example11
Loading editor…

General Purpose Tags

If test condition is true,Action-1 will be executed otherwise Action-2 will be executed.

Implementing switch statement:

Example12
Loading editor…

General Purpose Tags

1.<c:choose> should compulsory contains at least one <c:when> tag. But <c:otherwise> is optional.

  • Every <c:when> tag implicitly contains break statement. Hence there is no chance of fall through

inside switch.

  • We should take <c:otherwise> as last case only.

4.<c:choose> and <c:otherwise> won't take any attributes but <c:when> can take one mandatory

attribute test.

switch.jsp:

Example13
Loading editor…

General Purpose Tags

Example14
Loading editor…

16) Today is

Summary of Conditional Tags

TagDescriptionAttributes
1) <c:if>To implement Coretest, var, scope

Java if - Statement

Example15
Loading editor…

16) Today is

<c:when>To implementdoesn't contain any Attribute
<c:otherwise> if - else &but <c:when> should contain
switch stmtonly one Attribute i.e. test
Example16
Loading editor…

Iteration Tags

1.<c:forEach>:

form-1:

Example17
Loading editor…

Iteration Tags

o/p: 10 times

<c:forEach begin="1" end="10" step="2" > 5 times

<c:forEach begin="4" end="0" step="-1" > Invalid b'z step value should not be -ve.

The begin attribute specifies the index where the loop has to start.

end index specifies the index where the loop has to terminate.

This loop internally maintains counter variable which is incremented by step attribute value.

The default value of step attribute is "1" and it is optional attribute.

form-2: <c:forEach> with var attribute:

<c:forEach> internally maintains a counter variable which can be accessed by using var attribute.

This variable is local variable. Hence from outside of for loop we cannot access.

test.jsp:

Example18
Loading editor…

Iteration Tags

Example19
Loading editor…

Iteration Tags

Form-3: <c:forEach> for iterating through Arrays and Collections:

Example20
Loading editor…

Iteration Tags

Items attribute should be either Collection object or array object. This action will iterate over each

item in the collection until all elements completion.

We can represent current collection object by using var attribute.

Q. Write a JSP to print all elements of array:

test.jsp:

Example21
Loading editor…

Iteration Tags

Q. Write a JSP to print all request headers information:

test.jsp:

Example22
Loading editor…

Iteration Tags

Q. Write a JSP to print all request parameters information:

test.jsp:

Example23
Loading editor…

Iteration Tags

http://localhost:7777/jsp1/forEach2A.jsp?user=durga&age=48&course=java&mail=durgaocjp@g

mail.com

Form-4: <c:forEach> with varStatus attribute:

varStatus attribute describes the status of iteration like current iteration number, is it first

iteration or not etc..

This attribute is of type javax.servlet.jsp.core.TagLoopStatus.

This class contains several methods which are useful during iteration.

Example24
Loading editor…

Iteration Tags

returns the current item

Example25
Loading editor…

Iteration Tags

returns the current index(counter value)

Example26
Loading editor…

Iteration Tags

returns the number of iterations that have already performed.

Example27
Loading editor…

Iteration Tags

Returns true if the current Iteration is the First iteration

Example28
Loading editor…

Iteration Tags

Returns true if the current iteration is the last iteration

Example29
Loading editor…

Iteration Tags

returns start index

Example30
Loading editor…

Iteration Tags

returns end index

Example31
Loading editor…

Iteration Tags

returns the incremented value

test.jsp:

Example32
Loading editor…

Iteration Tags

It is a specialized version of forEach to perform StringTokenization based on some delimiter. It acts

as StringTokizer. We can store current token by using var attribute.

test.jsp:

Example33
Loading editor…

Iteration Tags

<c:forTokens> can accept the following extra attributes also.

begin: specifies the index at which iteration should start. The index of first token is zero.

end: specifies the index where iteration should be terminated.

step: counter increment value between iterations

varStatus: to specify the status of iteration

test.jsp:

Example34
Loading editor…

Iteration Tags

Note:

In the case of <c:forTokens>, items attribute should be String only. But in the case of <c:forEach>

the items attribute can be Collection, Array, Map OR String. Hence <c:forTokens> is considered as

specialized version of <c:forEach>

Summary of Iteration Tags

TagDescriptionAttributes
1) <c:foreach>General Purpose for Loopitems, begin, end, step, var, VarStatus
Example35
Loading editor…

Iteration Tags

VarStatus

URL Related Tags

Example36
Loading editor…

Iteration Tags

We can use this tag for importing the response of other pages in the current page response at

request processing time.(i.e. Dynamic Include)

Form-1:

<c:import url="second.jsp" />

Eg:

first.jsp:

Example37
Loading editor…

Iteration Tags

<h1>The FREE videos are available in www.durgasoftvideos.com</h1>

Form-2:

We can import response from outside of current application also.(i.e cross context communication

is possible)

<c:import url="/second.jsp" context="/webapp2" />

url and context should be specified with absolute Path only i.e should starts with "/"

Form-3:

We can store the result of imported page into a variable specified by var attribute. In the rest of

the JSP, where ever that result is required we can use directly that variable without importing

once again.

test.jsp:

Example38
Loading editor…

Iteration Tags

Another way to store the result of <c:import> is to use Reader object. It is alternative to var

attribute.

<c:import url="second.jsp" varReader="r" scope="page" />

Form-5:

While performing import we can send form parameters also to the Target JSP. For this we have to

use <c:param> tag. These parameters are available as form parameters in the target JSP.

first.jsp:

Example39
Loading editor…

Iteration Tags

<h1> The offered courses are : ${param.c1} and ${param.c2}

2.<c:redirect>:

This action can be used to redirect the request to another page. This is exactly similar to

sendRedirect() method of ServletResponse.

Form-1:

<c:redirect url="second.jsp" />

url can be specified either with Relative path or absolute path

first.jsp:

Example40
Loading editor…

Iteration Tags

<h1>Hello this is Second JSP</h1>

If we send the request to first.jsp then second.jsp will provide response through redirection.

Form-2:

We can redirect request to some other web application's resources also.

<c:redirect url="/second.jsp" context="/webapp2" />

url and context should be specified with Absolute Path only i.e. should starts with "/"

Form-3:

While performing redirection we can pass form parameters also to target resource.

first.jsp:

Example41
Loading editor…

Iteration Tags

The offered courses are : ${param.c1} and ${param.c2}

3.<c:url>

We can use this standard action to rewrite urls to append session information and form

parameters.

Form-1:

<c:url value="second.jsp" var="x" scope="request"/>

The encoded url with sessionid will be stored inside x.

test.jsp:

Example42
Loading editor…

Iteration Tags

<c:url value="/second.jsp" context="/webapp2" var="x" scope="request"/>

Form-3:

Example43
Loading editor…

Iteration Tags

<h1>Offered courses are : ${param.c1} and ${param.c2}</h1>

Summary of URL related Tags

TagDescriptionAttributes
1) <c:import>url, var, scope, varReader, context

For importing the Response of

Example44
Loading editor…

Iteration Tags

Web Components.

To rewrite URL for appending

Session Information &

Parameters (Form)

To send Parameters while

importing & redirecting.

Summary of All Core Library Tags:

Example45
Loading editor…

Iteration Tags

JSTL SQL Library

It defines several tags for communicating with database.

To make sql library available to JSP, we have to write the following taglib directive.

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

The following are important sql library tags

Example46
Loading editor…

Iteration Tags

To create DataSource

Example47
Loading editor…

Iteration Tags

To execute select query

Example48
Loading editor…

Iteration Tags

To execute non-select query(insert|delete|update)

Example49
Loading editor…

Iteration Tags

To provide parameter values in the case of PreparedStatement

Example50
Loading editor…

Iteration Tags

To provide date values in the case of PreparedStatement

Example51
Loading editor…

Iteration Tags

To implement transactions

Note: Transaction is a group of sql queries which will be executed on the policy "Either ALL or

None".

Note: It is not recommended to use JSTL SQL Library in our JSP, b'z JSP meant for presentation

logic but not for business logic and database logic.

test.jsp:

Example52
Loading editor…

Iteration Tags

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Example53
Loading editor…

Iteration Tags

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Example54
Loading editor…

Iteration Tags

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Example55
Loading editor…

Iteration Tags

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Example56
Loading editor…

Iteration Tags

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Example57
Loading editor…

Iteration Tags

JSTL Functional Library

It defines several tags for general String manipulation operations.

To use Functional Library,we have to write the following taglib directive in JSP.

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

The following are important tags in this library:

1.<fn:contains()>

Eg2:

split() method will split the given string according to the specified separator (delimiter)

join() method will join the given tokens into a single string based on separator.

Eg1:

Example58
Loading editor…

Iteration Tags

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Eg2:

Example59
Loading editor…

Iteration Tags

Example60
Loading editor…
📝 Key Takeaways
  • JSTL needs the jstl + standard JARs and a taglib directive
  • c:forEach exposes items, var and varStatus
  • JSTL lets you drop scriptlets from view pages

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.