6 JSTL EL - plor10/distributedJava GitHub Wiki
What is EL? § We use Scriptlets and JSP expressions to retrieve attributes and parameters in JSP with java code for the View. § For web designers, java code is hard to understand and that’s why JSP Specs 2.0 introduced Expression Language (EL) through which we can get attributes and parameters easily using HTML like tags. § Expression language syntax is ${name} and we will see how we can use them in JSP code
JSP EL Implicit Objects IMPLICIT OBJECTS DESCRIPTION pageScope A map that contains the attributes set with page scope. requestScope Used to get the attribute value with request scope. sessionScope Used to get the attribute value with session scope. applicationScope Used to get the attributes value from application scope. param Used to get the request parameter value, returns a single value paramValues Used to get the request param values in an array, useful when request parameter contain multiple values. header Used to get request header information. headerValues Used to get header values in an array. cookie Used to get the cookie value in the JSP initParam Used to get the context init params, we can’t use it for servlet init params pageContext Same as JSP implicit pageContext object, used to get the request, session references etc. example usage is getting request HTTP Method name
JSP EL Operators
1.
EL Property Access Operator or Dot (.) Operator
JSP EL Dot operator is used to get the attribute values.
JSP EL Operators
2.
JSP EL [] Operator or Collection Access Operator
[] operator is more powerful than dot operator. We can use it to get data from
Lists and Arrays too.
Some examples;
JSP EL Operators 3. JSP EL Arithmetic Operators Arithmetic operators are provided for simple calculations in EL expressions. They are + ,
, * , / or div , % or mod . 4. JSP EL Logical Operators They are && ( and ), || ( or ) and ! ( not ). 5. JSP EL Relational Operators They are
( eq ), != ( ne ), < ( lt ),
( gt ), <= ( le ) and
= ( ge
JSP EL Implicit Objects JSP EL OPERATOR PRECEDENCE FROM HIGHEST TO LOWEST [ ] . () – Used to change the precedence of operators. – ( unary ) not ! empty
- / div % mod
– ( binary ) < > <= >= lt gt le ge == != eq ne && and || or ? :
JSP EL Operators JSP EL Reserve Words and or not eq ne lt gt le ge true false null instanceof empty div,mod
JSP EL Operators 1. EL expressions are always within curly braces prefixed with $ sign, for example ${expr} 2. We can disable EL expression in JSP by setting JSP page directive isELIgnored attribute value to TRUE . 3. JSP EL can be used to get attributes, header, cookies, init params etc , but we can’t set the values. 4. JSP EL implicit objects are different from JSP implicit objects except pageContext , don’t get confused. 5. JSP EL pageContext implicit object is provided to get additional properties from request, response etc , for example getting HTTP request method.
JSP EL Operators 6. JSP EL is NULL friendly, if given attribute is not found or expression returns null, it doesn’t throw any exception. For arithmetic operations, EL treats null as 0 and for logical operations, EL treats null as false. 7. The [] operator is more powerful than dot operator because we can access list and array data too, it can be nested and argument to [] is evaluated when it’s not string literal. 8. If you are using Tomcat, the EL expressions are evaluated using org.apache.jasper.runtime.PageContextImpl .proprietaryEvaluate () method. 9. We can use EL functions to call method from a java class, more on this in custom tags post in near future.
JSTL Core ̈ < c:out
Like <%= ... > , but for expressions. ̈ < c:set
Sets the result of an expression evaluation in a
'scope'
<%@
taglib
prefix = "c"
uri
= "http://
java.sun.com
/
jsp
/
jstl
/core" %>
<
c:set
var
= "salary" scope = "session" value = "${2000*27}"/>
JSTL Core ̈ < c:if
Simple conditional tag which evaluates its body if
the supplied condition is true.
<
c:set
var
= "salary" scope = "session" value = "${2000*27}"/>
Big Number
c:if > $54000 Big NumberJSTL Core ̈ < c:choose
Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by and . ̈ < c:when
Subtag of that includes its body if its condition evaluates to 'true'. ̈ < c:otherwise
Subtag of that follows the tags and runs only if all of the prior conditions evaluated to 'false'.
JSTL Core < c:set var = "price" scope = "session" value = "${18000}"/> < c:choose
< c:when test = "${price <= 15000}"> That has to be a used car. </ c:when
< c:when test = "${salary > 40000}"> Very luxurious. </ c:when
< c:otherwise
Normal </ c:otherwise
</ c:choose
Norma
JSTL Core ̈ < c:forEach
The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality . < c:forEach var = " i " begin = "1" end = "5"> Item < c:out value = "${ i }"/>
</ c:forEach
Item 1 Item 2 Item 3 Item 4 Item 5
JSTL Core ̈ < c:forEach
The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality . < c:forTokens items = " Zara,nuha,roshy " delims = "," var = "name"> < c:out value = "${name}"/>
</ c:forTokens
Zara nuha Roshy
JSTL Core ̈ < c:import
Retrieves file from its URL and assigned
its
contents
to either the page, a String in
'
var
', or a Reader in '
varReader
'.
<
c:import
var
= "data"
url
= "http://
www.tutorialspoint.com
"/>
<
c:out
value = "${data}"/>
!DOCTYPE html> <!
<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils , Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Apache Commons Collections</title> www.photofuntoos.com "/><! -- [if IE 9]> <![endif] -- <! -- [if gt IE 9]><! --
JSTL Formatting Tags ̈ < fmt:formatNumber
To render numerical value with specific precision or format . ¤ Value Numeric value to display ¤ type NUMBER, CURRENCY, or PERCENT ¤ pattern Specify a custom formatting pattern for the output. ¤ currencyCode Currency code (for type = "currency") ¤ currencySymbol Currency symbol (for type = "currency") ¤ maxFractionDigits Maximum number of fractional digits to print ¤ minFractionDigits Minimum number of fractional digits to print ¤ var Name of the variable to store the formatted number
JSTL Formatting Tags ̈ 0 Represents a digit. ̈ E Represents in exponential form. ̈
Represents a digit; displays 0 as absent. ̈ . Serves as a placeholder for a decimal separator. ̈ , Serves as a placeholder for a grouping separator. ̈ ; Separates formats. ̈
Used as the default negative prefix. ̈ % Multiplies by 100 and displays as a percentage. ̈ ? Multiplies by 1000 and displays as per mille . ̈ X Indicates that any other characters can be used in the prefix or suffix. ̈ ' Used to quote special characters in a prefix or suffix.
JSTL Formatting Tags ̈ < fmt:formatNumber
<
fmt:formatNumber
value="${
balance}"
type="
currency
"/>
<
fmt:formatNumber
type="
number"
maxIntegerDigits
="
3"
value=
"
< fmt:formatNumber type=" number" groupingUsed =" false" value= "${balance}" />< br
< fmt:formatNumber type=" percent" maxIntegerDigits ="3" value= "${balance}" />< br
< fmt:formatNumber
Currency in USA : < fmt:setLocale value=" en_US "/> < fmt:formatNumber value="${ balance}" type=" currency"/>
Currency in USA : $120,000.23JSTL Formatting Tags ̈ < fmt:formatDate
Formats a date and/or time using the supplied styles and pattern. ̈ < fmt:parseDate
Parses the string representation of a date and /or time
JSTL CORE <%@ page import=" java.io ., java.util ., java.sql ."%> <%@ page import=" javax.servlet.http ., javax.servlet .*" %> <%@ taglib uri =" http:// java.sun.com / jsp / jstl /core" prefix=" c"%> <%@ taglib uri =" http:// java.sun.com / jsp / jstl / sql " prefix=" sql "%>
< sql:setDataSource
Creates
a simple
DataSource
suitable
only for
prototyping.
<
sql:setDataSource
var
="
snapshot"
driver="
com.mysql.jdbc.Driver
"
url
="
jdbc:mysql
://localhost/TEST"
user="
user_id
"
password="
mypassword
"/
< sql:query
Executes the SQL query defined in its body or through the sql attribute . < sql:query dataSource ="${snapshot}" var ="result"> SELECT * from Employees; </ sql:query
< c:forEach var ="row" items="${ result.rows }"> < tr > tr > c:forEach >
| < c:out value="${ row.id }"/> | < c:out value="${ row.first }"/> | < c:out value="${ row.last }"/> |
JSTL Functions ̈<%@ taglib uri =" http:// java.sun.com / jsp / jstl /functions" prefix =" fn " %> fn:contains () Tests if an input string contains the specified substring. ̈ fn:containsIgnoreCase () Tests if an input string contains the specified substring in a case insensitive way . ̈ fn:endsWith () Tests if an input string ends with the specified suffix.
JSTL Functions < c:set var =" theString " value="Test String"/> < c:if test="${ fn:contains ( theString , 'test')}"> Found test string </ c:if
< c:if test="${ fn:containsIgnoreCase ( theString , 'test ')}"> Found test string Ignore </ c:if
< c:if test="${ fn:endsWith ( theString , ' ing ')}"> String ends with 123 </ c:if
JSTL Functions ̈ fn :indexOf () Returns the index withing a string of the first occurrence of a specified substring. ̈ fn:substring () Returns a subset of a string . ̈ fn :length () Returns the number of items in a collection , or the number of characters in a string.
JSTL Functions < c:set var ="email" value="[email protected]"/> < c:set var =" loc " value='${ fn:indexOf (email, "@")}'/> Location of @ : ${ fn:indexOf (email, "@")}< br
Length of Email : ${ fn:length (email )}< br
Account : ${ fn:substring (email, 0, loc )} < br>