Nearby lessons
28 of 30JSP Examples - JSTL
- 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.
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" %>
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:
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:
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
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:
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:
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
| Tag | Description | Attribute |
|---|---|---|
| 1) <c:out> | Value, default, | |
| For writing Expression | escapeXml | |
| 2) <c:set> | and Template Text to JSP | var, value, scope |
target, property
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:
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:
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.
General Purpose Tags
If test condition is true,Action-1 will be executed otherwise Action-2 will be executed.
Implementing switch statement:
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:
General Purpose Tags
16) Today is
Summary of Conditional Tags
| Tag | Description | Attributes |
|---|---|---|
| 1) <c:if> | To implement Core | test, var, scope |
Java if - Statement
16) Today is
| <c:when> | To implement | doesn't contain any Attribute |
|---|---|---|
| <c:otherwise> if - else & | but <c:when> should contain | |
| switch stmt | only one Attribute i.e. test |
Iteration Tags
1.<c:forEach>:
form-1:
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:
Iteration Tags
Iteration Tags
Form-3: <c:forEach> for iterating through Arrays and Collections:
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:
Iteration Tags
Q. Write a JSP to print all request headers information:
test.jsp:
Iteration Tags
Q. Write a JSP to print all request parameters information:
test.jsp:
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.
Iteration Tags
returns the current item
Iteration Tags
returns the current index(counter value)
Iteration Tags
returns the number of iterations that have already performed.
Iteration Tags
Returns true if the current Iteration is the First iteration
Iteration Tags
Returns true if the current iteration is the last iteration
Iteration Tags
returns start index
Iteration Tags
returns end index
Iteration Tags
returns the incremented value
test.jsp:
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:
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:
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
| Tag | Description | Attributes |
|---|---|---|
| 1) <c:foreach> | General Purpose for Loop | items, begin, end, step, var, VarStatus |
Iteration Tags
VarStatus
URL Related Tags
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:
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:
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:
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:
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:
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:
Iteration Tags
<c:url value="/second.jsp" context="/webapp2" var="x" scope="request"/>
Form-3:
Iteration Tags
<h1>Offered courses are : ${param.c1} and ${param.c2}</h1>
Summary of URL related Tags
| Tag | Description | Attributes |
|---|---|---|
| 1) <c:import> | url, var, scope, varReader, context |
For importing the Response of
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:
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
Iteration Tags
To create DataSource
Iteration Tags
To execute select query
Iteration Tags
To execute non-select query(insert|delete|update)
Iteration Tags
To provide parameter values in the case of PreparedStatement
Iteration Tags
To provide date values in the case of PreparedStatement
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:
Iteration Tags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Iteration Tags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Iteration Tags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Iteration Tags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Iteration Tags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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:
Iteration Tags
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Eg2:
Iteration Tags
- 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