Expression Language in JSP 2.0

SHARE & COMMENT :

1)Introduction

Expression Language was first introduced in JSTL 1.0 (JSP Standard Tag Library ). Before the introduction of JSTL, scriptlets were used to manipulate application data.JSTL introduced the concept of an expression language (EL) which simplified the page development by providing standerd tag libraries. These tag libraries provide support for common, structural tasks, such as: iteration and conditionals, processing XML documents, internationalization and database access using the Structured Query Language (SQL).

also read:

The Expression Language introduced in JSTL 1.0 is now incorporated in JavaServer Pages specification(JSP 2.0). This articie gives some idea about what is Expression Language and how to simplify the maintenance for JSP applications by avoiding scripting elements.

2)Expression Language

The pattern that identifies Expression Language is ${ }. To deactivate the evaluation of EL expressions, we specify the isELIgnored
attribute of the page directive:

<%@ page isELIgnored ="true|false" %>

The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.

Operators which can be used in EL expression

Operator    Description
    .         Access a bean property or Map entry.
    []         Access an array or List element.
    ()         Grouping of a subexpression for evaluation order.
    ? :         Conditional test: condition ? ifTrue : ifFalse.
    +         Addition.
    -         Subtraction.
    *         Multiplication.
    /or div     Division.
    % or mod M    Modulo (remainder).
    == or eq     equality.
    != or ne     inequality.
    < or lt     less than.
    > or gt     greater than.
    <= or le     less than or equal.
    >= or ge     greater than or equal.
    && or and     logical AND.
    || or or     logical OR.
    ! or not     Unary Boolean complement.
    empty         Test for null,empty String,array or Collection.
    func(args)     A function call.
  • Arithmetic operators.
     Before JSP2.0/JSTL 
    <%! int k = 0; %> <% k = 10 + 20; out.println("value of k is.."+k); %> 
    Using JSP2.0/JSTL (without using scriptlet) 
    value of k is ${10 + 20} 

    Few more examples on arthmetic operations.

     EL Expression			Result	
    ${10.2 + 20.3} 			O/P: 30.5 
    ${-40 - 20} 			O/P: -60 
    ${20 * 2} 			O/P: 40 
    ${3/4} 				O/P: 0.75 
    ${3 div 4} 			O/P: 0.75 
    ${10/0} 			O/P: Infinity 
    ${50%8} 			O/P: 2 
    ${50 mod 8} 			O/P: 2 
    ${(10==20) ? "true" : "false"} 	O/P: false 
  • comparison operators.
      Numeric EL Expression 		Result 
    ${10 (4/2)} 			false 
    ${1 gt (4/2)} 			false 
    ${4.0 >= 3} 			true 
    ${4.0 ge 3} 			true 
    ${40 <= 30} 			false 
    ${40 le 30} 			false 
    ${10 == 10} 			true 
    ${100 eq 100} 			true 
    ${(5*20) != 100} 		false 
    ${(5*20) ne 100} 		false 
    
    Alphabetic EL Expression	Result
    ${'a' 3} 			true 
  • EL implicit objects
     Identifier		Description
    pageContext 		PageContext instance 
    pageScope 		Map-associates name and values of page-scoped attributes 
    requestScope 		Map-associates name and values of request-scoped attributes 
    sessionScope 		Map-associates name and values of session-scoped attributes 
    applicationScope 	Map-associates name and values of application-scoped attributes 
    parametersparam 	Map-stores the primary values of the request parameters by name 
    paramValues 		Map-stores all values of the request parameters as String arrays 
    header 			Map-stores the primary values of the request headers by name 
    headerValues 		Map-stores all values of the request headers as String arrays 
    cookie 			Map-stores the cookies accompanying the request by name 
    initParam 		Map-stores the context initialization params of the appln by nam
  • Note:EL impilcit objects are not as same as the implicit objects available for JSP scripting except for pageContext.JSP and EL implicit objects have only one object in common (pageContext),and pageContext has properties for accessing all of the other eight JSP implicit objects.The first four maps represent the various attribute scopes which can be used to look up identifiers in specific scopes. The next four maps are for fetching the values of request parameters and headers.The cookie implicit object provides access to the cookies set by a request and the final EL implicit object, initParam, is a map storing the names and values of any context initialization parameters associated with the Web application.Lets look at few examples on how to use implicit objects.
     First.jsp 		
    First Name: <input type='text' name='Name'/> 
    Last Name: <input type='text' name='Address'/> 
    <input type='submit' value='Submit'/> 
    
    Second.jsp 
    Name is : ${param.Name} 
    Address is : ${param.Address}
    Similarly 
    
    Header Key : ${header.key} 
    Header Value : ${header.value} 

    Here in First.jsp we are entering the details of Name and Address, when we click on submit button the flow goes to Second.jsp.
    We can retrieve the values by using ${param.xxxx}

  • Scope Examples:
     Accessing a page-scoped attribute named as firstName: ${pageScope.firstName} Accessing a request-scoped attribute named as firstName: ${requestScope.firstName} Accessing a session-scoped attribute named as 'lastName' (null if not found): ${sessionScope.lastName} 
  • Page Context Examples
     ${pageContext.request.protocol} ${pageContext.response.locale} ${pageContext.session.id} ${pageContext.servletContext} 

    Above we are accessing request, response, session, and application properties, using the pageContext implicit object.

  • Cookie Example:
     addCookies.java 
    Cookie c=new Cookie("name","test"); 
    res.addCookie(c); 
    
    Test.jsp 
    Name : ${cookie["name"]}
    Value : ${cookie["name"].value} 

    Here in addCookies.java we are creating a new Cookie,These values can be retrieved in jsp by using ${cookie.xxxx}.

  • Init Parameter Example
     XML: 
    <context-param> 
    <param-name>email</param-name> 
    <param-value>Hello@xyz.com</param-value> 
    </context-param> 
    
    Test.jsp email is: ${initParam.email}  
  • Functions
    Defining Functions:The JSP expression language allows you to define a function that can be invoked in an expression. Functions are defined using the same mechanisms as custom tags.

     public class MyFunctions { public static String toCaps( String text ) { return text.toUpperCase(); } } 

    Using Functions:

     XML: <uri>testFunctionsURI</uri> 
    <function> <name>toCaps</name> 
    <function-class>mypkg.MyFunctions</function-class> 
    <function-signature>String toCaps( java.lang.String)</function-signature> 
    </function> 
    
    JSP: <%@ taglib prefix="myFunctionTest" uri="testFunctionsURI"%> ${myFunctionTest.toCaps("testingCaps")} 

Conclusion

By using this expression language, page authors could drastically reduce the amount of scripting in their pages, resulting in greater productivity, easier maintenance, and a flatter learning curve in terms of page development. Over the years, the expression language has evolved to include more advanced functionality, while still maintaining its simplicity.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better