Expression Language (EL) is a scripting language which allows access to Java components (JavaBeans) through JSP. Since JSP 2.0, it has been used inside JSP tags to separate Java code from JSP, and to allow easier access to Java components (than in Java code).

Evolution of EL occurred to make scripting easier for web-content designers who have little or practically no knowledge of the core Java Language. This scripting language makes JSP a scripting language in the true sense. Before EL, JSP consisted of some special tags like scriptlets, expressions etc within which Java code was written explicitly. With EL the web-content designer needs only to know how to make proper calls to core Java methods and can enjoy the true scripting flavour of a scripting language.

EL is, both syntactically and semantically, similar to JavaScript expressions:

  • there is no typecasting
  • type conversions are usually done implicitly
  • double and single quotes are equivalent
  • object.property has the same meaning as object['property']

EL also liberates the programmer from having to know the particularities of how the values are actually accessed: object.property can mean (depending on what the object is) either object.get("property") or object.getProperty("property") or object.getProperty() etc.

[edit]See also

  • OGNL- An open source expression language used by WebWork (and Struts2).
  • MVEL- Another open source EL used in many Java-based projects.

[edit]External links








Unified Expression Language


The Java Unified Expression Language is a special purpose programming language mostly used in Java web applications for embedding expressions into web pages. The Java specification writers and expert groups of the Java web-tier technologies have worked on a unified expression language which was first included in the JSP 2.1 specification (JSR-245), and later specified by itself in jsr-341, part of Java EE 7.

History[edit]

The expression language started out as part of the JavaServer Pages Standard Tag Library (JSTL) and was originally called SPEL (Simplest Possible Expression Language), then just Expression Language (EL). It was a scripting language which allowed access to Java components (JavaBeans) through JSP. Since JSP 2.0, it has been used inside JSP tags to separate Java code from JSP, and to allow easier access to Java components (than in Java code).

Over the years, the expression language has evolved to include more advanced functionality and it was included in the JSP 2.0 specification. Scripting was made easier for web-content designers who have little or practically no knowledge of the core Java Language. This scripting language made JSP a scripting language in the true sense. Before EL, JSP consisted of some special tags like scriptlets, expressions etc. within which Java code was written explicitly. With EL the web-content designer needs only to know how to make proper calls to core Java methods.

EL was, both syntactically and semantically, similar to JavaScript expressions:

  • there is no typecasting
  • type conversions are usually done implicitly
  • double and single quotes are equivalent
  • object.property has the same meaning as object['property']

EL also liberated the programmer from having to know the particularities of how the values are actually accessed: object.property can mean (depending on what the object is) eitherobject.get("property") or object.getProperty("property") or object.getProperty() etc.

During the development of JSP 2.0, the JavaServer Faces technology was released which also needed an expression language, but the expression language defined in the JSP 2.0 specification didn't satisfy all the needs for development with JSF technology. The most obvious limitation is that its expressions are evaluated immediately. And also, the JSF components need a way to invoke methods on server-side objects. A more powerful language was created with the following new features:

  • Deferred expressions, which are not immediately evaluated
  • Expressions that can set as well as get data
  • Method expressions, which can invoke methods

The new expression language worked well for the purposes of JSF. But developers had problems when integrating the JSP EL with the JSF EL because of conflicts. Because of these incompatibilities, the unified expression language initiative was started to unify these expression languages. As of JSP 2.1, the expression languages of JSP 2.0 and JSF 1.1 have been merged into a single unified expression language (EL 2.1).

Version 3.0 of the expression language (the unified was no longer deemed necessary) was developed in a JSR independent of the JSP and JSF specifications in JSR-341 . Some new features were added, most notably EL equivalents of Java 7's streams and lambda expressions.[1]

Features[edit]

The new unified EL is a union of the JSP and JSF expression languages. In addition to the features already available in the JSP EL, the unified EL has the following features:

  • Deferred evaluation
  • Support for expressions that can set values and expressions that can invoke methods
  • A pluggable API for resolving expressions

Examples[edit]

This shows a simple example of Unified EL being used within a JSTL "c:out" tag:

<c:out value="${myBean.myField}" />

An expression that calls a method with a parameter:

${myBean.addNewOrder('orderName')}

Implementations[edit]

  • JUEL is an open-source implementation of the Unified Expression Language 2.1. It is considered stable and feature complete and is licensed under the Apache License 2.0. JUEL is also suitable for use in non-JSP applications.
  • Apache Commons EL is the JSP 2.0 EL interpreter from Apache.

See also[edit]

  • OGNL - An open source EL used by WebWork (and Struts2).
  • MVEL - An open source EL used in many Java-based projects.
  • Apache Commons JEXL - An open source EL intended to facilitate the implementation of dynamic and scripting features for Java-based projects
  • SpEL - Spring Expression Language, an open source EL that is part of the Spring Framework. It's mainly used in Spring portfolio projects but because it's technology-agnostic it may be used in other projects.

External links[edit]

References[edit]



출처 - http://en.wikipedia.org/wiki/Unified_Expression_Language








I would like to know the detailed difference between the Expression Languages (EL). There is JSP EL, JSF EL and Unified EL.

I would like to know the history behind the EL and what the latest EL is that is used in Java EE applications. Is it the EL common for all view technologies in the latest versions?


  • Jun 2002: JSTL 1.0 was introduced with EL for first time. It were those ${} things which works in JSTL tags only. It is designed to call Javabean get methods.

  • Nov 2003: JSP 2.0 was introduced and EL was moved from JSTL 1.0 to JSP 2.0 in javax.servlet.jsp.el package and it became standard EL as part of J2EE 1.4 standard. JSTL 1.1 was shipped without EL. Now ${} works outside JSTL tags in JSP template text as well.

  • Mar 2004: JSF 1.0 was introduced with deferred EL in javax.faces.el package. It were those #{} things which works inside JSF tags only. The difference with standard JSP EL ${} is that it doesn't only do get, but can also do set. This was mandatory for managed bean auto-creation and setting the values of input components. The standard EL ${} works in JSF output tags as well, but they won't auto-create beans if they don't exist in scope yet and they won't set input values.

  • May 2005: While still preparing for new JSP 2.1 which should be released May 2006, deferred EL #{} was extracted from JSF and combined with standard EL ${} in the javax.el package. At that point, it became unified EL which was introduced with JSF 1.2 and became later part of JSP 2.1 and Java EE 5 standard. The #{} can now also be used in JSP tags to get values, but not toset values..

  • Nov 2006: Facelets was introduced as successor of JSP. It allowed for use of #{} in template text outside JSF tags, as substitute for <h:outputText> without any attributes. It also treats ${} as #{}, so they both behave the same in Facelets.

  • Dec 2009: EL 2.2 was introduced with JSP 2.2 / Java EE 6 which now allows for calling concrete bean action methods instead of only calling Javabean getters/setters inside #{} syntax, e.g. #{bean.method(argument)}. Facelets became part of Java EE 6 standard.


Adding to BalusC's answer...

EL was originally conceived by and implemented by Nathan Abramson of Art Technology Group in 2001. At the time the implementation was known as Simplest Possible Expression Language (SPEL). The implementation was later included in the JSTL1.0. Nathan was part of the JSR-052 Expert Group, and was credited in the JSTL specification as the driving force behind the expression language.

"Special mention to Nathan Abramson for being a driving force behind the expression language introduced in JSTL"



출처 - http://stackoverflow.com/questions/4812755/difference-between-jsp-el-jsf-el-and-unified-el








◈ EL(Expression Language)

- Jsp 2.0에서 부터 제공 되는 기능이다.

- 화면 출력을 위해서만 제공되는 기능

- 간단한 연산자를 사용할 수 있고 parameter 값을 출력할 수 있다.

- Jsp내부의 변수, 반환형이 있는 메서드는 출력이 안된다.

- Jsp Tag 내에서는 사용할 수 없다.

- HTML영영에서만 사용할 수 있다.


 사용법

 ${ 연산자 } //간단한 연산자( 산술, 관계, 삼항)

 ${ param.컨트롤명 } //파라메터값 출력


<%@page import="util.HangulConv"%>

<%@page import="java.net.URLEncoder"%>

<%@ page language="java" info="2012. 3. 9. aaa EL의사용" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"

isELIgnored="false"%>

<!-- isELIgnored="false(EL사용,EL이해석된결과출력),

true(EL사용안함,EL이그대로출력)" -->

<!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=UTF-8">

<title>Insert title here</title>

<script type="text/javascript">

 

</script>

<link rel="stylesheet" type="text/css" href="http://localhost:8080/jsp_prj/common/css/main.css"/>

</head>

<body>

 

산술연산자의사용:

3+9=<b>${3+9}</b><br/>

102로나눈나머지<b>${10%2 }</b>

 

관계연산자의사용(결과는true/false) :

3&gt;2 = <b>${3>2}</b> <br/>

 

삼항연산자의사용(결과는true/false) :

10은짝수냐홀수냐<b>${10%2==0짝수":"홀수" }</b><br/>

<%-- 쉬프트연산자는사용할수없다.2&lt;&lt;3 = ${2<<3 } --%>

<!-- get방식의 url 만들고encoding 되지않은한글을넘겨주면

&name=철수 localhost 테스트하는경우받아질수도있지만

domain 가지고서비스하게되면한글이제대로넘어오지않는다. -->

<href="el.jsp?today=2012-03-09&name=<%=URLEncoder.encode("철수","utf-8"%>">파라메터요청</a><br/>

파라메터출력<br/>

오늘날짜<b>${param.today }</b><br/>

<!-- EL에서는자바에서제공하는클래스를사용할수없다.

이름: <b>${param.name }</b>-->

이름<b><%=HangulConv.toUTF(request.getParameter("name")) %></b>

</body>

</html>


출처 - http://blog.naver.com/sexyboy789?Redirect=Log&logNo=10133884991









EL(expression language)

사용법

일반적으로 아무 설정없이 사용가능하지만 EL태그 인식이 안될 경우 다음과 같이 속성을 추가해 준다.

  1. <%@ page isELIgnored="false" contentType = "text/html; charset=euc-kr" %>

 

형식

  1. ${...}

EL 표현식은 항상 중괄호로 묶고 제일 앞에 달러($)기호를 붙입니다.

 

도트(.) 연산자 사용

  1. ${person.name}
  1. 표현식에서 도트 연산자 왼쪽은 반드시 맵 또는 빈이여야 함
  2. 표현식에서 도트 연산자 오른쪽은 반드시 맵의 키이거나 빈 프로퍼티여야 합
  3. 오른쪽에 오는 값은 식별자로서 일반적인 자바 명명 규칙을 따라야 합니다.  

 

[] 연산자 사용

도트 연산자는 왼쪽에는 맵이나 빈 밖에 올 수 없으며, 오른쪽에 오는 것도 자바 명명 규칙을 따라야 합니다.

그러나 []연산자는 왼쪽에 리스트나 배열도 올 수 있습니다.

  1. ${musicList["something"]} 
  1. []연산자의 왼편에는 맵, 빈, 배열, 리스트 변수가 올 수 있습니다. 
  2. []연산자 안의 값이 문자열(따옴표로 묶여 있다면) 이라면, 이것은 맵 키가 될 수 있고, 빈 프로퍼티 또는 리스트나 배열 인덱스가 될 수 있습니다. 

 

빈과 맵이라면 둘 다 사용가능
  1. ${musicMap.Ambient}
  2. ${musicMap["Ambient"]}

 

문자열이 아닐경우
  1. 1. ${musicMap[Ambient]}
  2. 2. ${musicMap["Ambient"]}
  1. 문자열이 아닐경우 평가하여 Ambient라는 속성이 있을 경우 이 속성의 값을 키 값으로 사용한다.
  2. 문자열일 경우 단순히 Ambient라는 이름의 키 값을 찾는다.

 

포함 관계일 필요는 없다.
  1. ${musicList[number[0]} 

먼저 number라는 속성에서 값을 찾고 musicList[찾은값]으로 다시 값을 찾기 때문에 musicList에 number가 들어있지 않아도 된다.

 

EL에서 param 속성

해당 파라미터 이름으로 값이 하나 밖에 없을 때 EL 내장 객체인 param을 사용하면 그 값을 읽을 수 있음.

  1. ${param.name} 

 

하지만 해당 파라미터의 이름으로 그 값이 하나 이상일 때는 param 대한 paramValues를 사용

  1. ${paramValues.food[0]}
  2. ${paramValues.food[1]}

 

EL 내장 객체

  1. 생존범위 속성 맵

    1. pageScope 
    2. requestScope 
    3. sessionScope 
    4. applicationScope 
  2. 요청 파라미터 맵 

    1. param 
    2. paramValues 
  3. 요청 헤더 맵 

    1. header 
    2. headerValues 
  4. 쿠키 맵 

    1. cookie 
  5. 컨텍스트 초기화 파라미터 맵(서블릿 초기화 파라미터 아님) 

    1. initParam 
  6. 실제 pageContext 객체에 대한 참조. 이것은 빈임

    1. pageContext

      1. pageContext 접근자

        1. getErrorData() 
        2. getPage() 
        3. getRequest() 
        4. getResponse() 
        5. getServletConfig)() 
        6. getServletContext() 
        7. getSession() 
      2. JspContext로 부터 상속받은 접근자

        1. getAttribute() 
        2. getAttributeNamesInScope() 
        3. getAttributesScope()
        4. getExpressionEvaluator() 
        5. getOut() 
        6. getVariableResolver() 

 

 Request에서 파라미터 이상의 정보를 원할 때?

host 헤더 정보 읽기

스크립팅

  1. <$= request.getHeader("host") %>

EL 내장 객체

  1. ${header["host"]}
  2. ${header.host}
  3. ${headerValues.host[]}

 

HTTP 요청 메소드가 무엇인지 알기

스크립팅

  1. <%= request.getMethod() %>

EL 내장 객체

  1.  ${pageContext.request.method}

 

 requestScope와 request 객체는 다른 녀석

requestScope는 request 정보(property)가 아닌, request 속성을 가져오기 위해 사용함.

request 정보는 pageContext를 통해서 접근할 수 있음...

기타 나머지 모든 정보를 읽기 위해서는 pageContext를 사용함.

 

생존범위 관련 내장 객체가 도움이 될 때

명시적으로 코딩을하면 이름 충돌을 피할 수 있다.

  1. ${requestScope.person.name}

자바 명명 규칙을 지키지 않은 속성에 접근 할 수 있다.

  1. request.setAttribute("foo.person", p);
  2. ${requestScope["foo.person"].name}

 

쿠키에서 값을 출력

스크립팅

  1. <%
  2. Cookie[] cookies = request.getCookies();
  3. for(int i = 0; i< cookies.length; i++){
  4. if((cookies[i].getName()).equals("userName")){

  5. out.println(cookies[i].getValue());

  6. }

  7. }
  8. %>

EL

  1. ${cookie.userName.value} 

 

기타 정보 출력 예

  1. ip: ${pageContext.request.remoteAddr}<br>
    method : ${pageContext.request.method}<br>
    cookie : ${cookie}
    protocol : ${pageContext.request.protocol}

 

컨텍스트 초기화 파라미터 값을 출력

DD

  1. <context-param>
  2. <param-name>mainEmail </param-name>

  3. <param-value>email@email.com</param-value>

  4. </context-param>

스크립팅

  1. <%= application.getInitParameter("mainEmail") %>

EL

  1. ${initParam.mainEmail} 

 initParam은 DD의 <init-param>으로 설정된 값을 읽어오는 것이 아니라 <context-param>을 사용함. 헷갈리게 이름지어졌음...

 

 

EL 함수

  1. 정적인 공용 메서드를 제공하는 클래스를 먼저 작성 
  2. 태그 라이브러리 서술자 파일을 만듭 
  3. JSP에 taglib 지시자를 코딩 
  4. 함수를 호출하는 EL을 작성합니다. 

 

함수를 정의한 클래스

  1. package foo;
  2. public class DiceRoller{
  3. public static int rollDice(){

  4. return (int) ((Math.random() * 6) + 1);

  5. }

  6. }

태그 라이브러리 서술자(.tld)

  1. <?xml version="1.0" encoding="euc-kr" ?>
    <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
  2.     http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd>
       
    <taglib>
        <tlib-version>1.2</tlib-version>
          <uri>DiceFunction</uri>   // 태그 라이브러리의 uri와 동일
  3. <function>

  4. <name>rollIt</name>      // 사용될 함수의 이름

  5. <function-class>foo.DiceRoller</function-class>   // 실제 클래스 경로

  6. <function-signature>int rollDice()</function-signature>   // 실제 클래스의 메소드

  7. </function>

  8. </taglib>

JSP

  1. <%@ taglib prefix="mine" uri="DiceFuncfions" %>   
  2. // prefix: 해당 페이지에서 쓸 별첨 같은 것
  3. // uri: 태그 라이브러리 이름이 들어가는 부분, jsp가 EL함수를 호출하면 컨테이너가 어떤 메소드를 호출할지 찾을 때 이를 사용함.
  4. ${mine:rollIt()}   // 사용

 

 배포

WEB-INF에 TDL를 넣고 CLASS 파일을 넣으면 됨

 

기타

  1. EL 함수는 리턴 타입이 void 라도 관계없음
  2.  컨테이너는 WEB-INF 를 뒤져서 모든 .tld 파일을 찾음
  3. EL 함수가 인자를 갖기위해선 인자로 들어갈 클래스 이름을 TLD에 완전한 경로로 기입하면 됨
  1. <function-signature>
  2. int rollDice(java.util.Map)

  3. </function-signature>

 

 

<jsp:useBean>

<jsp:getProperty>를 사용하기 위해 실제 객체를 선언하고 초기화하는 태그

 

  1. <jsp:useBean id="person" class="foo.Person" type="foo.Person" scope="request" />

 

  1. jsp:useBean : 표준액션입을 나타냄
  2. id : 빈 객체 식별자를 선언
  3. class : 빈 객체의 클래스 타입을 선언함.
  4. type : 참조 변수의 타입을 지정, 추상 클래스, 인스턴스, 클래스 등을 사용 가능함.
  5. scope : 빈 객체 속성 생존범위를 지정함. 기본값은 page 

 


출처 - http://lazyartist.springnote.com/pages/788330








Posted by linuxism
,