Expression Language

     Cornelius Koo, ST
        JavaSchool
           2005
 Jl. Cemara 2/20, Salatiga
Why EL
public void doPost( HttpServletRequest req,
                  HttpServletResponse res) throws
                           ServletException, IOException {
       Human p = new Human();
       p.setName("Evan");

      Dog dog = new Dog();
      dog.setName("Spike");
      p.setDog(dog);

      req.setAttribute("person", p);

      RequestDispatcher rd =
             req.getRequestDispatcher("withscript.jsp");
      rd.forward(req,res);
}
<body>
<%= ((jsp.example.bean.Human)
  request.getAttribute("person")).getDog().get
  Name() %>

<jsp:useBean id="person"
  class="jsp.example.bean.Human"
  scope="request"/>
  Dog's name is : <jsp:getProperty
  name="person" property="dog"/>
</body>
Result
• Spike Dog's name is :
  jsp.example.bean.Dog@1e0e954
EL
• Dog's name is : ${person.dog.name}
Result
• Dog's name is : Spike
EL Rules
1st n 2nd
• ${ firstThing.secondThing }

• firstThing -> EL Implicit Object or attribute

• secondThing -> a property
EL Implicit Objects
•   pageScope               map objects
•   requestScope            map objects
•   sessionScope            map objects
•   applicationScope        map objects
•   param                   map objects
•   paramValues             map objects
•   header                  map objects
•   headerValues            map objects
•   cookie                  map objects
•   initParam               map objects
•   pageContext ->real reference to pageContext object
Accessing EL
If the expression has a variable followed by a dot, the left-hand
variable MUST be a Map or a bean
The Thing on the right must follow normal Java naming rules for
identifiers
If the expression has a variable followed by a bracket [ ], the left-
hand variable can be a Map, a bean, a List or an array.
If the thing inside the brackets is a String literal (i.e., in quotes), it
can be a Map key or a bean property, or an index into a List or array.
• In Servlet

String[] nameList = { “Aan”, “Sam”, “John”};
request.setAttribute(“name”, nameList);
• In JSP

Name : ${name}
Name : ${name[0]}
Name : ${name[“0”]}
Using [] for bean
• In Servlet

Map musicMap = new HashMap();
musicMap.put(“Ambient”, “Zero”);

request.setAttribute(“musicMap”,musicMap);
• In JSP

• ${musicMap.Ambient}
• ${musicMap[“Ambient”]}
What About This ?
• ${musicMap[Ambient]}

• This time with no “ “
• In Servlet

Map musicMap = new HashMap();
musicMap.put(“Ambient”, “Zero”);

request.setAttribute(“musicMap”,musicMap);
request.setAttribute(“Genre”,”Ambient”);
• In JSP

• ${musicMap[“Genre”]} -> doesn’t work

• ${musicMap[Genre]} -> evaluated
  because there’s an attribute object named
  Genre and it has a value named “Ambient”
Nesting
• ${musicMap[ musicType[0] ]}

• ${musicMap[“Ambient”]}

• Zero 7
Don’t try…
• Don’t put everything that are not qualified
  as an identifiers behind the dot (.)
  operator!

• ${musicMap[“Ambient”]} -> ${musicMap.Ambient}

• ${musicList[“1”]} -> X ${musicList.1}
Request Parameter in EL
• In HTML

<form action=“TestBean.jsp”>
  Name : <input type=“text” name=“name”>
  ID# : <input type=“text” name=“empID”>
  <input type=“submit”>
</form>
• In JSP

• ${param.name}
• ${param.empID}
Request Method
• With expression
<%= request.getMethod() %>

• With EL
${pageContext.request.method}
Getting Request Attribute
• In Servlet
request.setAttribute(“person”, p);

• Get it with EL
${requestScope[“person”].name}
Header Information
• With expression
<%= request.getHeader(“host”) %>

• With EL
${header.host}
${header.[“host”]}
Cookie
• With scriptlet
<% Cookie[] cookies = request.getCookies();
  for(int i=0; i < cookie.length; i++) {
       if ((cookies[i].getName()).
                       equals(“username”)) {
                out.println(cookies[i].getValue());
       }
  }
%>

• With EL
${cookie.userName.value}
Init Parameter
• DD
<context-param>
   <param-name>name</param-name>
   <param-value>Rod Johnson</param-value>
</context-param>

• With expression
<%= application.getInitParameter(“name”) %>

• With EL
${initParam.name}
Method in EL
package jsp.example.method;

public class DiceRoller {
  public static int rollDice() {
      return (int) ((Math.random()*6)+1);
  }
}

The method must be public and static
el.tld

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC
   "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
   "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
    <tlibversion>1.2</tlibversion>
    <jspversion>2.0</jspversion>
    <uri>DiceFunctions</uri>
    <function>
          <name>rollIt</name>
          <function-class>jsp.example.method.DiceRoller</function-class>
          <function-signature>int rollDice()</function-signature>
    </function>
</taglib>
method.jsp

<%@ taglib prefix="method" uri="DiceFunctions" %>
<html>
<head>
<title>EL Method</title>
</head>

<body>
  ${method:rollIt()}
</body>
</html>
ELOperator
Arithmetic
•   +
•   -
•   *
•   /
•   %
Logical
• && or and
• || or or
• ! or not
Relational
•   == or eq
•   != or ne
•   < or lt
•   > or gt
•   <= or le
•   >= or ge

Expression Language in JSP

  • 1.
    Expression Language Cornelius Koo, ST JavaSchool 2005 Jl. Cemara 2/20, Salatiga
  • 2.
  • 3.
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Human p = new Human(); p.setName("Evan"); Dog dog = new Dog(); dog.setName("Spike"); p.setDog(dog); req.setAttribute("person", p); RequestDispatcher rd = req.getRequestDispatcher("withscript.jsp"); rd.forward(req,res); }
  • 4.
    <body> <%= ((jsp.example.bean.Human) request.getAttribute("person")).getDog().get Name() %> <jsp:useBean id="person" class="jsp.example.bean.Human" scope="request"/> Dog's name is : <jsp:getProperty name="person" property="dog"/> </body>
  • 5.
    Result • Spike Dog'sname is : jsp.example.bean.Dog@1e0e954
  • 6.
    EL • Dog's nameis : ${person.dog.name}
  • 7.
  • 8.
  • 9.
    1st n 2nd •${ firstThing.secondThing } • firstThing -> EL Implicit Object or attribute • secondThing -> a property
  • 10.
    EL Implicit Objects • pageScope map objects • requestScope map objects • sessionScope map objects • applicationScope map objects • param map objects • paramValues map objects • header map objects • headerValues map objects • cookie map objects • initParam map objects • pageContext ->real reference to pageContext object
  • 11.
  • 12.
    If the expressionhas a variable followed by a dot, the left-hand variable MUST be a Map or a bean
  • 13.
    The Thing onthe right must follow normal Java naming rules for identifiers
  • 14.
    If the expressionhas a variable followed by a bracket [ ], the left- hand variable can be a Map, a bean, a List or an array.
  • 15.
    If the thinginside the brackets is a String literal (i.e., in quotes), it can be a Map key or a bean property, or an index into a List or array.
  • 16.
    • In Servlet String[]nameList = { “Aan”, “Sam”, “John”}; request.setAttribute(“name”, nameList);
  • 17.
    • In JSP Name: ${name} Name : ${name[0]} Name : ${name[“0”]}
  • 18.
  • 19.
    • In Servlet MapmusicMap = new HashMap(); musicMap.put(“Ambient”, “Zero”); request.setAttribute(“musicMap”,musicMap);
  • 20.
    • In JSP •${musicMap.Ambient} • ${musicMap[“Ambient”]}
  • 21.
    What About This? • ${musicMap[Ambient]} • This time with no “ “
  • 22.
    • In Servlet MapmusicMap = new HashMap(); musicMap.put(“Ambient”, “Zero”); request.setAttribute(“musicMap”,musicMap); request.setAttribute(“Genre”,”Ambient”);
  • 23.
    • In JSP •${musicMap[“Genre”]} -> doesn’t work • ${musicMap[Genre]} -> evaluated because there’s an attribute object named Genre and it has a value named “Ambient”
  • 24.
    Nesting • ${musicMap[ musicType[0]]} • ${musicMap[“Ambient”]} • Zero 7
  • 25.
    Don’t try… • Don’tput everything that are not qualified as an identifiers behind the dot (.) operator! • ${musicMap[“Ambient”]} -> ${musicMap.Ambient} • ${musicList[“1”]} -> X ${musicList.1}
  • 26.
  • 27.
    • In HTML <formaction=“TestBean.jsp”> Name : <input type=“text” name=“name”> ID# : <input type=“text” name=“empID”> <input type=“submit”> </form>
  • 28.
    • In JSP •${param.name} • ${param.empID}
  • 29.
    Request Method • Withexpression <%= request.getMethod() %> • With EL ${pageContext.request.method}
  • 30.
    Getting Request Attribute •In Servlet request.setAttribute(“person”, p); • Get it with EL ${requestScope[“person”].name}
  • 31.
  • 32.
    • With expression <%=request.getHeader(“host”) %> • With EL ${header.host} ${header.[“host”]}
  • 33.
  • 34.
    • With scriptlet <%Cookie[] cookies = request.getCookies(); for(int i=0; i < cookie.length; i++) { if ((cookies[i].getName()). equals(“username”)) { out.println(cookies[i].getValue()); } } %> • With EL ${cookie.userName.value}
  • 35.
  • 36.
    • DD <context-param> <param-name>name</param-name> <param-value>Rod Johnson</param-value> </context-param> • With expression <%= application.getInitParameter(“name”) %> • With EL ${initParam.name}
  • 37.
  • 38.
    package jsp.example.method; public classDiceRoller { public static int rollDice() { return (int) ((Math.random()*6)+1); } } The method must be public and static
  • 39.
    el.tld <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPEtaglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.2</tlibversion> <jspversion>2.0</jspversion> <uri>DiceFunctions</uri> <function> <name>rollIt</name> <function-class>jsp.example.method.DiceRoller</function-class> <function-signature>int rollDice()</function-signature> </function> </taglib>
  • 40.
    method.jsp <%@ taglib prefix="method"uri="DiceFunctions" %> <html> <head> <title>EL Method</title> </head> <body> ${method:rollIt()} </body> </html>
  • 41.
  • 42.
    Arithmetic • + • - • * • / • %
  • 43.
    Logical • && orand • || or or • ! or not
  • 44.
    Relational • == or eq • != or ne • < or lt • > or gt • <= or le • >= or ge