Expression Language in jsp

Chapter 7 - Building JSP Pages Using the Expression Language (EL)

    Expression Language in jsp

  • Expression Language

    An EL expression used to evaluated JSP with the syntax ${},EL expression whose evaluation is deferred is represented with the syntax #{}.

    The first named variable is always either an implicit object or an attribute such as in page, request, session or application scope.

    EL Implicit objects:

    pageScope requestScope sessionScope maps of scoped attributes
    param paramValues map of request parameters, param return only first value if there are multiple. paramValues returns array/list of values.
    header
    headerValues
    map of request headers, header return only first value if there are multiple. headerValues returns array/list of values.
    cookie map of cookies
    initParam map of CONTEXT init parameters
    pageContext instance of PageContext class.

     

    • dot operator (e.g. ${person.name}): left operand must be Map or bean. Right operand must be Map key or bean property and follow Java Identifier rule (variable naming rule).
    •  [] operator (e.g. ${person["name"]}): left operand must be Map or bean or List or array. Right operand, if inside quotes "" can be Map key, bean property or index into a List or array, else will be evaluated as a EL Expression and the result will be used as key, property or index.
    • [] operator allows NESTED expression.
    • When attribute contained dot (e.g. "foo.bar"), use [] operator.
    • EL Function:

    1) Define a public static method (e.g. public static int stud() )

    2) Inside TLD file:

            
                < function >
    < name > functionName < /name >
    < function-class > full_class_name_of_public_static_method < /function-class >
    < function-signature > int rollDice() < function-signature >
    < /function >

    Function signature may take in parameters. All data type in function-signature must be fully qualified.

    3) Use taglib directive to reference to the TLD

    4) Invoke function:

     ${taglibprefix:functionName()}
    
    •  Other EL operators:
    +
    -
    *
    / or DIV
    % or MOD

    EL treat null as 0

    Division by 0 return INFINITY ???
    Remainder of division by 0 yields exception.

    && and and
    || and or
    ! and not
    EL treat null as false
    == and eq
    != and ne
    < and lt
    > and gt
    >= and ge
     
    •   Other reserved keywords: true, false, null, instanceof, empty.
    •   EL treats unknown variable as null. ???
    •   Invalid operand makes logical expression evaluated to false or exceptions are thrown.

    Several implicit objects available to EL expressions:

    pageContext - the PageContext object. Provides an API to access various objects including:

    o context - the context for the JSP page's servlet and any Web components contained in the same application.

    o session - the session object for the client.

    o request - the request triggering the execution of the JSP page.

    pageScope - a java.util.Map that maps page-scoped attribute names to their values.

    requestScope - a java.util.Map that maps request-scoped attribute names to their values.

    sessionScope - a java.util.Map that maps session-scoped attribute names to their values.

    applicationScope - a java.util.Map that maps application-scoped attribute names to their values.

    param - a java.util.Map that maps parameter names to a single String parameter value (obtained by calling ServletRequest.getParameter(String name)).

    paramValues - a java.util.Map that maps parameter names to a String[] of all values for that parameter (obtained by calling ServletRequest.getParameterValues(String name)).

    header - a java.util.Map that maps header names to a single String header value (obtained by calling HttpServletRequest.getHeader(String name)).

    headerValues - a java.util.Map that maps header names to a String[] of all values for that header.

    cookie - a java.util.Map that maps cookie names to a single Cookie object. Cookies are retrieved according to the semantics of HttpServletRequest.getCookies().

    initParam - a java.util.Map that maps context initialization parameter names to their String parameter value (obtained by calling ServletContext.getInitParameter(String name)).

    JSP EL Example:

    JSP EL Example

    package com.journaldev.model;
    
    public interface Person {
     
     public String getName();
     public void setName(String nm);
    }
    package com.journaldev.model;
    
    public class Address {
    
     private String address;
    
     public Address() {
     }
    
     public String getAddress() {
      return address;
     }
    
     public void setAddress(String address) {
      this.address = address;
     }
     
     public String toString(){
      return "Address="+address;
     }
    }
    package com.journaldev.model;
    
    public class Employee implements Person {
    
     private String name;
     private int id;
     private Address address;
    
     public Employee() {
     }
    
     @Override
     public String getName() {
      return this.name;
     }
    
     @Override
     public void setName(String nm) {
      this.name = nm;
     }
    
     public int getId() {
      return id;
     }
    
     public void setId(int id) {
      this.id = id;
     }
    
     public Address getAddress() {
      return address;
     }
    
     public void setAddress(Address address) {
      this.address = address;
     }
     
     @Override
     public String toString(){
      return "ID="+id+",Name="+name+",Address="+address;
     }
    
    }
    

    Employee and Address are java beans with no-args constructor and getter-setter methods for properties. It provides implementation of toString() method in JSP Pages:

    package com.journaldev.servlet;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.journaldev.model.Address;
    import com.journaldev.model.Employee;
    import com.journaldev.model.Person;
    
    @WebServlet("/HomeServlet")
    public class HomeServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
           
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //Setting some attributes
      Person person = new Employee();
      person.setName("Pankaj");
      
      request.setAttribute("person", person);
      
      Employee emp = new Employee();
      Address add = new Address();
      add.setAddress("India");
      emp.setAddress(add);
      emp.setId(1);
      emp.setName("Pankaj Kumar");
      
      HttpSession session = request.getSession();
      session.setAttribute("employee", emp);
      
      response.addCookie(new Cookie("User.Cookie","Tomcat User"));
      getServletContext().setAttribute("User.Cookie","Tomcat User");
      
      RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp");
      rd.forward(request, response);
     }
    
    }
    

    Some context init params in web.xml:

    
    

    < ?xml version="1.0" encoding="UTF-8"? >
    < web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" >
      < display-name>JSPELExample
     
      < context-param >
       < param-name > AppID < /param-name >
       < param-value > 123 < /param-value >
       < /context-param >
     
    < /web-app >

    JSP code using EL to create views:

    
    

    < %@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII" import="java.util.*"%>
    < !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
    < html >
    < head >
    < meta http-equiv="Content-Type" content="text/html; charset=US-ASCII" >
    < title>JSP EL Example Home < /title >
    < /head >
    < body >
    < %     List < String > names = new ArrayList < String >();
        names.add("Pankaj");names.add("David");
        pageContext.setAttribute("names", names);
    % gt
    Simple . EL Example:< /strong > ${requestScope.person}
    < br > < br >
    < strong > Simple . EL Example without scope:< /strong > ${person}

    < br >
    < strong > Simple [] Example: < /strong > ${applicationScope["User.Cookie"]}
    < br > < br >
    < strong > Multiples . EL Example: < /strong > ${sessionScope.employee.address.address}
    < br > < br >
    < strong > List EL Example: < /strong > ${names[1]}
    < br > < br >
    < strong > Header information EL Example: < /strong > ${header["Accept-Encoding"]}
    < br > < br >
    < strong > Cookie EL Example: < /strong > ${cookie["User.Cookie"].value}
    < br > < br >
    < strong > pageContext EL Example: < /strong > HTTP Method is ${pageContext.request.method}
    < br > < br >
    < strong > Context param EL Example: < /strong > ${initParam.AppID}
    < br > < br >
    < strong > Arithmetic Operator EL Example: < /strong > ${initParam.AppID + 200}
    < br > < br >
    < strong > Relational Operator EL Example: < /strong > ${initParam.AppID < 200}
    < br > < br >
    < strong > Arithmetic Operator EL Example: < /strong > ${initParam.AppID + 200}
    < br > < br >
    < /body >
    < /html >

© 2015 by Learncertification All Rights Reserved. The certification names are the trademarks of their respective owners. Terms & Privacy Policy