6 expression language
TRANSCRIPT
-
7/27/2019 6 Expression Language
1/46
Expression Language
-
7/27/2019 6 Expression Language
2/46
-
7/27/2019 6 Expression Language
3/46
Scriptless JSP
A JSP page without any scriptlets is a script-less JSP.
Our attempt is to reduce the clutter of java code in
the JSP so that the page designers do not have the
burden of learning java and also maintenancebecomes easy.
With standard jsp action tags we can achieve some
script-less-ness.
But surely this is not enough.
For instance how will you print request parameters in a
script-less way?
-
7/27/2019 6 Expression Language
4/46
JSP that uses standard JSP tags to access User object named userthat has been stored in the session object:
First Name :
Last Name :
eMail Address :
-
7/27/2019 6 Expression Language
5/46
The same JSP that uses EL:
First Name :
${user.firstName}
Last Name :${user.lastName}
eMail Address :
${user.emailAddress}
-
7/27/2019 6 Expression Language
6/46
Need for EL
Take another example-
Suppose we have a class Car which has an attribute
called engine of class Engine.
Let us attempt to display the attribute of the engine
object given the Car object but in a scriptless way.
-
7/27/2019 6 Expression Language
7/46
public class Car{
Engine engine;
String model;//other attributes
//getters and setters methods
}
class Engine{String engine_type;
int engine_cc;
//other attributes.
public getEngine_type(){}public getEngine_cc
// other getter and setter methods.
}
-
7/27/2019 6 Expression Language
8/46
Attempts to display engines engine_type attribute
Using standard actions
Engine Type:
NO THIS WILL RESULT IN AN ERROR
-
7/27/2019 6 Expression Language
9/46
Using scripting
THIS IS FINE BUT REMEMBER WE
SAID WE WILL ATTEMPT SCRIPTLESS
JSP.
SO WE CONCLUDE
STANDARD ACTIONSARE NOT ENOUGH TOMAKE JSP SCRIPTLESS
-
7/27/2019 6 Expression Language
10/46
EL to rescue!
Using EL to solve the problem
${car.engine.engine_type}
instead of
But what is EL?
-
7/27/2019 6 Expression Language
11/46
EL
Expression language
Primary feature of JSP technology version 2.0
EL expressions can be used:
In static text
The value of an el expression in static text is computedand inserted into the current output
In any standard or custom tag attribute that can accept anexpression
If the static text appears in a tag body, the expressionwill not be evaluated if the body is declared to betagdependent
We will see what this is in the custom tag section
-
7/27/2019 6 Expression Language
12/46
EL Syntax
EL implicit Object OR an
attribute either in page,
request, session or application
scope (searched in that
sequence)
If E1 is implicit object , then
E2 is Attribute
If E1 is Attribute, then E2 is
the property of the object.
${E1.E2}
-
7/27/2019 6 Expression Language
13/46
ExampleBean
package com.jft;import java.io.Serializable;
public class Emp implements Serializable{private String empno;private String name;public Emp(){empno="402";
name="Rama";}public void setEmpno(String empno){this.empno=empno;}
public void setName(String name){this.name=name; }
public String getEmpno(){return empno;}
public String getName(){return name;
}}
-
7/27/2019 6 Expression Language
14/46
elexample5.jsp
DisplaysMr. Rama 402
The expressions are evaluated from left to right. Each
expression is evaluated to a String and then concatenated
with any intervening text. The resulting String is then
coerced to the attribute's expected type.
-
7/27/2019 6 Expression Language
15/46
EL Implicit Objects
pageScope
requestScope
sessionScope
applicationScope
param
paramValues
header
headerValues cookie
initParam
pageContext
Map objects
Note that these objects are
not the same as JSP implicit
object
Like JSP implicit object
-
7/27/2019 6 Expression Language
16/46
-
7/27/2019 6 Expression Language
17/46
Using . Operator
When the variable is on the left side of the dot, it is
either a Map(Key/Value pair) or a bean(properties)
${E1.E2}
Map(java.util.Map)
Key
Java bean class
property
-
7/27/2019 6 Expression Language
18/46
Examples
We have seen an example for java bean withproperty
${a.name}
Map Example${pageScope.a.name} Where pageScope is implicit object of map type.
-
7/27/2019 6 Expression Language
19/46
Using [ ] operator
When the variable is on the left side of the [], it can
be
Map
bean
List
array
-
7/27/2019 6 Expression Language
20/46
${E1[E2]}
Map(java.util.Map)
Key
Java bean class
property
List(java.util.List)
index
array
index
In case of List and arrays , String index is forced(converted) to an int.
-
7/27/2019 6 Expression Language
21/46
Ex1: [] Operator with JavaBean property
Servlet Code(jsp in scriptlet)
User user = new User(firstName, lastName, emailAddress);
session.setAttribute(user, user);
JSP Code
Hello ${user[firstName]}
Ex2: [] Operator with an ArrayServlet Code
String[] colours = {red, green, blue};
ServletContext application = this.getServletContext();
application.setAttribute(colours, colours);JSP Code
First colour is ${colours[0]}
Second colour is ${colours[2]}
Second colour is ${colours[2]}
Third colour is ${colours[3]}
-
7/27/2019 6 Expression Language
22/46
Ex3: [] Operator with a List
Servlet Code
ArrayList users = UserIO.getUsers(path);
session.setAttribute(users, users);
JSP Code
First address in the List:${users[0].emailAddress}
Second adderss in the List:${users[1].emailAddress}
First address in the List:${users[0].emailAddress}
Second adderss in the List:${users[1].emailAddress}
-
7/27/2019 6 Expression Language
23/46
Example using [] and .
protected void doGet(){java.util.Map carmap=newjava.util.HashMap();
carmap.put("Large","Mercedes");carmap.put("Medium","Getz");
carmap.put("Small","Alto");String[] cartype={"Large","Medium","Small"};
request.setAttribute("carmap",carmap);request.setAttribute("cartype",cartype);request.setAttribute("size","Medium");
request.getRequestDispatcher("i2.jsp").forward(request,response);
}
I JSP
-
7/27/2019 6 Expression Language
24/46
My car is: ${carmap.Large}
orMy car is: ${carmap["Large"]}
Car type : ${cartype[0]} or Car type :
${cartype["1"]}
My car is: ${carmap[size]}My car is:${carmap[cartype[0]]}
Both print Mercedes
prints Large
prints Medium
prints Getz. Without double
quotes inside the square
brackets the string value istreated as attribute. The
attribute evaluates and its
value is substituted.
prints Mercedes
In JSP
-
7/27/2019 6 Expression Language
25/46
Question?
Write an EL to print the session id.
${pageContext.session.id}EL implicit object
${session.id} No session in EL implicit object
-
7/27/2019 6 Expression Language
26/46
Question?
Suppose that there is a size attribute set in the
session scope as well. Write an EL Expression to print
the size attribute in the session scope?
${pageContext.session.size}
${size}
${sessionScope.size}
This returns the request scopes size
-
7/27/2019 6 Expression Language
27/46
Getting other parameters
${cookie.uname.valu}
Returns the value of uname cookie
${initParam.color}
Can you write EL to get the parameters from theform.
-
7/27/2019 6 Expression Language
28/46
Form Params
${param.eno}
Gets the request parameter matching eno
${paramValues.hobbies}
Gets the first value from the multiple value
request attribute
${paramValues.hobbies[0]}
Same as the above You could also say${param.eno[0]} for a single
value parameter.
-
7/27/2019 6 Expression Language
29/46
elexample1.jsp
Enter name:
elexample2.jsp
Welcome, ${param.name}
-
7/27/2019 6 Expression Language
30/46
elexample3.jsp
Welcome to index page
visit
elexample4.jsp
Value is ${sessionScope.user}
-
7/27/2019 6 Expression Language
31/46
How to get an HTTP Header
JSP Code
Browser MIME Types: ${header.accept}
Browser compression types: ${header[accept-encoding]}
How to work with Cookies
Servlet Code
Cookie c = new Cookie(emailCookie, emailAddress);
c.setMaxAge(60*60);
c.setPath(/);
response.addCookie(c);
JSP Code
The eMail Cookie : ${cookie.emailcookie.value}
This works because the Cookie class follows all the rules for the
JavaBean, and includes a method named getValue() that can be
used to get the value thats stored within the cookie
-
7/27/2019 6 Expression Language
32/46
How to get a context initialization parameter
web.xml
myEmail
JSP Code
The context init parameter: ${initParam.myEmail}
How to use pageContext Object
JSP Code
HTTP Request Method: ${pageContext.request.method}
HTTP Response Type:${pageContext.response.contentType}
HTTP Session ID: ${pageContext.session.id}
HTTP contextPath:${pageContext.servletContext.contextPath}
-
7/27/2019 6 Expression Language
33/46
EL Operators Arithmetic Operators
+
- *
/,div${42/0} gives INFINITY as output and notException
% ,mod
${42%0} gives an Exception
In arithmetic expressions, EL treats the
unknown variable (null value) as Zero(0).
-
7/27/2019 6 Expression Language
34/46
Relational Operators
==, eq
!=, ne
< , lt
> , gt
=, ge
Logical Operators
&& , and AND
|| , or OR
!, not NOT
In Logical expressions (using logical operatorsand/or relational operator, EL treats the unknown
variable (null value) as false.
-
7/27/2019 6 Expression Language
35/46
EL reserved words
and eq gt true instanceofor ne le false emptynot lt ge null div mod
Note:${empty obj} returns true if obj is null orempty.
-
7/27/2019 6 Expression Language
36/46
Examples
-
7/27/2019 6 Expression Language
37/46
EL Functions
Suppose you need to display the number of times this
jsp page has been visited and you have a static
method countIt() that returns this value. How would
you invoke this function in a scriptless way from jsp? The expression language allows a function to
be invoked in an expression provided the
function is defined as public static method in a
java class.
-
7/27/2019 6 Expression Language
38/46
Creating a class
public class Counter{static int count;
public static int countIt()
{ return count++;}//other class member definitions
}
TLD file
-
7/27/2019 6 Expression Language
39/46
TLD file
1.2
CountFunction
counterCounterint
countIt()
WEB-INF/ my.tld
-
7/27/2019 6 Expression Language
40/46
Use in JSP file
${mycnt:counter()}
Prefixmycntis just a name.
The container identifies the TLD through the uri (name
of TLD) in the taglib directive.
Di bli EL i JSP d DD
http://localhost/var/www/apps/conversion/tmp/scratch_5/EL.ppt -
7/27/2019 6 Expression Language
41/46
Disabling EL in JSP and DD In a jsp page we can disable the EL using the is ELIgnored
page directive attribute
In the DD we do it as
. . .
*.jsp
true
. . .
-
7/27/2019 6 Expression Language
42/46
Ensuring that JSPs are scriptless
*.jsp true
-
7/27/2019 6 Expression Language
43/46
emailListForm.jsp
-
7/27/2019 6 Expression Language
44/46
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
import com.jft.User1;
public class addEmailListServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Date currentDate = new Date();
request.setAttribute("currentDate", currentDate);
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
User1 user = new User1(firstName, lastName, emailAddress);
HttpSession session = request.getSession();
session.setAttribute("user", user);
RequestDispatcher rd = getServletContext().getRequestDispatcher("elexample7.jsp");
rd.forward(request, response); }
}
-
7/27/2019 6 Expression Language
45/46
Taglib Directive
Defines a tag library and prefix for the custom tagsused in the JSP page
Example:
..
-
7/27/2019 6 Expression Language
46/46
The directive declares that the JSP file usescustom tags, names the tag library that defines them, andspecifies their tag prefix.
----- taglib Directive
JSP has a set of standard tags for you to use. JSP also
provide a possibility to allow you to create new custom tagslook like HTML and XML tag. In this case, you can use taglibdirective to use your custom tag in your JSP page. For usingcustom tag, you can refer to the custom tag tutorial. Thesyntax of using taglib directive is as follows: