본문 바로가기

JSP/EL 02

EL 02

JSP에서 EL 표현식과 EL 함수를 사용하는 예


Cart.java

package shopping;
import java.util.*;

public class Cart {
 
 private Vector<String> v;
 
 public Cart() {
  v = new Vector<String>();
  v.add("MP3");
  v.add("PMP");
  v.add("DMB");
 }
 
 public int getItems(){
  return v.size();
 }
}


<%@ page language="java" contentType="text/html; charset=EUC-KR"%>

<jsp:useBean id="cart" class="shopping.Cart" scope="session"/>

<html>
<head>
<title>스코프 객체 안에 저장되어 있는 빈 객체를 접근하는 예제</title>
</head>
<body>

Expression을 사용한 경우:<%=cart.getItems()%><p>

EL을 사용한 경우(1): ${sessionScope.cart.items}<p>

EL을 사용한 경우(2):${cart.items}<p>

</body>
</html>



EL의 간략성
<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%
 session.setAttribute("cart", new shopping.Cart());
%>
<html>
<head>
<title>EL의 간략성</title>
</head>
<body>
<%
 shopping.Cart cart = (shopping.Cart)session.getAttribute("cart");
 int count = cart.getItems();
 out.println("장바구니 아이템 수:"+count);
%>
<p>
장바구니 아이템 수:${sessionScope.cart.items}<p>
장바구니 아이템 수:${cart.items}<p>
</body>
</html>



Forward하는 경우에 EL을 이용하면 좀더 간편하다.

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>

<% request.setAttribute("cart", new shopping.Cart()); %>

<jsp:forward page="cartView.jsp"/>


cartView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
 shopping.Cart cart = (shopping.Cart)request.getAttribute("cart");
 int count = cart.getItems();
 out.println("장바구니 아이템 수:"+count);
%>
<p>
장바구니 아이템 수:${requestScope.cart.items}<p>

장바구니 아이템 수:${cart.items}<p>
</body>
</html>



EL에서 제공하는 empty 연산자를 이용하면 파라미터의 유무를 판단할 때도 코드를 간략화할 수 있다.

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>

<html>
<head>
<title>EL을 이용한 파라미터 접근</title>
</head>
<body>

 ID: ${empty param.id}<p>
 
 ID: ${param.id} <p>
 
 Cookie: ${cookie.JSESSIONID}<p>

</body>
</html>


클래스의 static 메소드를 EL 안에서 호출할 수 있다. 다음 절차에 따라서 설정해 주면 EL안에서 함수호출이 가능하게 된다.

1. 다음과 같이 클래스를 선언하고 static 함수를 하나 선언한다.

package elfunc;

public class SampleFunc {
 public static String testFunc(String str){
  return "Hello "+str;
 }
}



2. /WEB-INF/functions.tld 파일을 생성하고 다음과 같이 작성한다.

<?xml version="1.0" encoding="UTF-8" ?>

<taglib version="2.0">   
  <tlib-version>1.1</tlib-version>
 
  <function>
    <description>Test Function</description>
    <name>testFunc</name>
    <function-class>elfunc.SampleFunc</function-class>
    <function-signature>java.lang.String testFunc(java.lang.String )</function-signature>
    <example>
        ${ f:testFunc("This is test") }
    </example> 
  </function>

</taglib>



3. 선언된 메소드를 사용하는 JSP파일을 작성한다.

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>

<%@ taglib prefix="f" uri="/WEB-INF/functions.tld"%>

<html>
<head>
<title>El Function test</title>
</head>
<body>

${ f:testFunc("This is test.") }

</body>
</html>