본문 바로가기

JSP/JSTL

Introduction to JSTL

JSTL 사용 예


<c:set>
JSP의 영역객체( pageContext, request, session, application )안에 데이터를 저장한다
<c:set var="hello" value="Hello World"/> 와 같은 방법으로 변수를 생성하는 것은 디폴트로 pageContext영역에 'hello' 란 이름으로 'Hello World'라는 값을 저장하는 것이다. 다른 영역에 저장하려면
<c:set var="hello" value="Hello World" scope="session"/>과 같은 방법을 사용하면 된다.
session.getAttribute("hell") 와 같은 코드를 이용해도 설정된 그 값에 접근할 수 있게 된다.

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/functions"%>
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>

<c:set var="hello" value="Hello World"/>
<c:out value="${hello}"/>
<br>
${hello}<br>

</BODY>
</HTML>


JSTL의 변수는 디폴트로 pageContext 영역객체에 저장된다.
scope 속성에서 영역을 지정하면 request, session, application등에도 저장할 수 있다.

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
 pageContext.setAttribute("p", new shopping.Cart());
 session.setAttribute("s", new shopping.Cart());
%>

<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>

<c:set var="p" value="Hello World"/>

\${pageScope.p} --> ${pageScope.p}<p>
\${p} --> ${p}<p>
\${sessionScope.s.items} --> ${sessionScope.s.items}<p>
</BODY>
</HTML>


<c:set ... scope="session"/> 세션영역에 데이터를 저장하고 다른 페이지에서 참조하는 예

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="id" value="${param.id}" scope="session"/>
<!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=EUC-KR">
<title>JSTL과 session 영역</title>
</head>
<body><br/><br/><center>
JSTL을 이용하여 session영역에 전달된 id를 저장했습니다<p/>
<a href="jstl_session02.jsp">다음 페이지로</a>
</center>
</body>
</html>



jstl_session02.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=EUC-KR">
<title>JSTL과 session영역</title>
</head>
<body><br/><br/><center>
전 페이지에서 전달되어 온 id=
${sessionScope.id}<br/>
<c:out value="${sessionScope.id}"/>
</center>
</body>
</html>


<c:set target="${obj} property="propName" value="${value}" />
useBean을 이용하여 생성한 Bean 객체나 영역에 저장된 객체, Map 등의 속성 값을 할당할 때 사용한다.

<jsp:useBean id="pageUtil" class="board.PageUtilBean" scope="page">
  <c:set target="${pageUtil}" property="currPage" value="${param.pg}"/>
  <c:set target="${pageUtil}" property="numsPerPage" value="${3}"/>
<%--<jsp:setProperty name="pageUtil" property="currPage" param="pg"/>
   <jsp:setProperty name="pageUtil" property="numsPerPage" value="2"/> --%>
</jsp:useBean>



<c:if test=""> ${ param.xxxx }

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% request.setCharacterEncoding("KSC5601"); %>
<html> 
<body bgcolor="lightblue"> 
<form method="post" action="jstl02.jsp"> 
    <select  name="combo1">
      <option value="sam">sam
      <option value="tom">tom
    </select>
 <input  type="submit">
</form>
<c:set var="s" value="${param.combo1}"/>
<c:out value="${s}"/>
<br> 

<c:if test="${s=='sam'}">
   <c:out value="Good Morning...SAM!"/>
</c:if>

<c:if test="${s=='tom'}"> 
  <c:out value=" How Are You?....TOM!"/> 
</c:if>

</body> 
</html>


<c:choose><c:when> <c:otherwise>

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% request.setCharacterEncoding("KSC5601"); %>

<html>
<body bgcolor=lightblue>
  <form   method=post  action="jstl03.jsp">
  <select name="combo1">
     <option value="1">1   </option>
     <option value="2">2   </option>
     <option value="3">3   </option>
     <option value="4">4   </option>
     <option value="5">5   </option>
     <option value="7">7   </option>
  </select>

  <input  type=submit value="전송">
  <c:set var="s"   value="${param.combo1}"  />
    Today is 
  <br>

<font size=24 color=red>

<c:choose> 
 <c:when  test="${s==1}">Sunday   </c:when> 
 <c:when  test="${s==2}">Monday</c:when> 
 <c:when  test="${s==3}">Tuesday</c:when> 
 <c:when  test="${s==4}">Wednesday</c:when> 
 <c:when  test="${s==5}">Thursday</c:when>

 <c:otherwise>
    select between 1 & 5    
 </c:otherwise>
</c:choose>
 
</body> 
</html>



EL에서 Bean, List, Map, 배열 다루는 방법
Bean객체일 경우 : ${ obj["attr"] }, ${ obj.attr }          ==> obj.getXXX() 호출됨
Map일 경우        : ${ map["key"] }, ${ map.key }    ==> map.get("key") 호출됨, 키가 한글일 경우에는 map.key는 영문만

List일 경우         : ${ list[0] }
배열일 경우        : ${ arr[0] }


<c:forEach> String[]

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
 pageContext.setAttribute("colors",
 new String[]{"red","green","blue","orange","black"} );  
%>

<table>
<c:forEach var="n" items="${colors}" varStatus="a">
<tr>
<td>   <c:out value="${a.index}"/> </td>   <!-- 0부터 시작되는 첨자-->
<td>   <c:out value="${a.count}"/> </td>   <!-- 1부터 시작되는 순번-->
<td>  <c:out value="${a.first}"/> </td>       <!-- 처음이면 true -->
<td>  <c:out value="${a.last}"/> </td>       <!-- 마지막이면 true -->
<td>   <c:out value="${a.current}"/> </td>  <!--현재의 값-->
<td>   \${n} : <c:out value="${n}"/> </td> <!-- value="${ colors[a.index] } 이렇게 해도 됨-->

</tr>
</c:forEach>
</table>

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
 pageContext.setAttribute("nums",new int[]{1,2,3,4,5,6,7,8,9});
 pageContext.setAttribute("dan",new int[]{2,3,4,5,6,7,8,9});
%>

<html><body><p><center>
<table border=0 cellspacing=0>

<c:forEach var="n" items="${nums}">
 <tr>
 <c:forEach var="d" items="${dan}">
  <td>&nbsp;${d} x ${n} = ${d*n}&nbsp;</td>
 </c:forEach><br>
 </tr>
</c:forEach>

</table>
</center>
</body></html>


<c:forEach> Custom Object, Vector

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%!
public class Goods{
 private String item;
 private int price;
 public Goods(String item, int price) {
  this.item = item;
  this.price = price;
 }
 public String getItem() {
  return item;
 }
 public int getPrice() {
  return price;
 }
}
%>
<%
 java.util.Vector<Goods> cart = new java.util.Vector<Goods>();
 cart.add(new Goods("노트북", 1200000));
 cart.add(new Goods("메모리", 120000));
 cart.add(new Goods("PMP", 200000));
%>

<c:set var="cart" value="<%=cart%>" scope="session"/>

<table>
<c:forEach var="g" items="${sessionScope.cart}">
 <tr>
  <td>   상품명 : <c:out value="${g.item}"/> </td>
  <td>   (가격 : <c:out value="${g.price}"/>) </td>
 </tr>
</c:forEach>
</table>


<c:forEach> begin, end

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>

<c:forEach    var="n"  begin="1"  end="9" >
    <c:out  value="7 * ${n} = ${7*n}"/><br> 
</c:forEach>

</BODY>
</HTML>


<c:forEach> ArrayList<String>

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=EUC-KR">
<title>JSTL FOR EACH for arrays</title>
</head>
<body><br/><br/><center>

<%
 java.util.ArrayList<String> list = new java.util.ArrayList<String>();
 list.add("강호동"); list.add("김종민"); list.add("이수근"); list.add("은지원");
%>

<c:forEach var="n" items="<%=list%>" varStatus="status">
 ${status.index+1}. ${status.current} ${n}<br/>
</c:forEach>

</center>
</body>
</html>



<c:forEach> HashMap, ArrayList<HashMap<String,String>>

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=EUC-KR">
<title>JSTL FOR EACH for Map</title>
</head>
<body><br/><br/><center>

<%
 HashMap<String,String> map = new HashMap<String,String>();
 map.put("num", "1"); map.put("name", "장미란"); map.put("phone", "2345-6543-567");
%>
<c:set var="m" value="<%=map%>"/>
번호: ${m.num} <br/>
이름: ${m.name} <br/>
전화: ${m.phone} <br/>
<p/>
<%
 HashMap<String,String> map2 = new HashMap<String,String>();
 map2.put("num", "2"); map2.put("name", "박지성"); map2.put("phone", "234-8657-678");
 ArrayList<HashMap<String,String>>list = new ArrayList<HashMap<String,String>>();
 list.add(map);
 list.add(map2);
%>
<c:forEach var="m" items="<%=list%>" varStatus="status">
 ${status.index+1}. ${m.num} ${m.name} ${m.phone}/${status.current.name}<br/>
</c:forEach>

</center>
</body>
</html>





<c:forEach> ArrayList<Board>

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page import="java.util.*" %>
<%@ page import="com.ojtit.test.board.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=EUC-KR">
<title>JSTL forEach with Board-List</title>
</head>
<body><br/><br/><center>
<%
 ArrayList<Board> list = new ArrayList<Board>();
 Board board = new Board();
 board.setSubject("게시판 테스트");
 list.add(board);
 board = new Board();
 board.setSubject("사랑합니다");
 list.add(board);
%>
<c:forEach var="b" items="<%=list%>">
 ${b.subject}<br/>
</c:forEach>
</center>
</body>
</html>



<c:forTokens>

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

  <c:set var="s" value="SAM,DELHI,MCA,24,90"  />
<html>
<body>
   <table border="1">
   <tr>
   <th>Name</th>
   <th>Place</th>
   <th>Degree</th>
   <th>Age</th>
   <th>Mark</th>
   </tr>
   <tr>
<c:forTokens     items="${s}" delims=","  var="token"  >
   <td><c:out value="${token}"  /></td>
</c:forTokens>
  </tr>
  </table>
  <br>
  </font>
</body>
</html>


HashMap

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ page import="java.util.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<h3>JSTL Map Accessing Test</h3>

<%
   java.util.HashMap map = new java.util.HashMap();
   map.put("key One", "value One");
   map.put("Two", "value Two");
   map.put("key Three", "value Three");
   map.put("key Four", "value Four");
   map.put("key Five", "value Five");
%>

<c:set var="map" var="<%=map%>"/>

<c:out value='${map["key One"]}'/><br>
<c:out value='${map.Two}'/><br>

<hr>

<c:forEach var='item' items='${map}'>
   <c:out value='Key=${item.key}, Value=${item.value}'/><br>
</c:forEach>

<hr>

<c:forEach var='item' items='${map}'>
   <c:out value='${item.key} : ${item.value}'/><br>
</c:forEach>

</body>
</html>


 <c:import> <jsp:include>의 기능과 유사하지만 다른 사이트의 내용까지도 포함할 수 있는 점에서 차이가 난다.

welcome.html

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>

<c:import url="welcome.html"/> <!-- 파일의 내용이 해석되어 화면에 출력됨-->
<c:out   value="to our web-site!" /><br>
----------------------------------------------------<br>
<c:import url="welcome.html" var="file"/>
<c:out value="${file}"/><!--파일의 내용인 코드가 출력됨--><br>
</BODY>
</HTML>



<c:import> <c:param>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=EUC-KR">
<title>JSTL import tag example</title>
</head>
<body>
<c:import url = "jstl_imported.jsp">
 <c:param name = "greeting" value = "<h1>사랑합니다</h1>"/>
</c:import>
</body>
</html>

jstl_imported.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<fmt:requestEncoding value="euc-kr"/>
<!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=EUC-KR">
<title>This file is imported</title></head>
<body>
 ${param.greeting}
</body>
</html>



<c:url> URL-Rewriting 에서 사용할 URL을 작성해준다, 파라미터가 포함된 URL으로 링크를 연결할 때 유용할 것이다.

<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>
<a href="<c:url value='http://localhost/jstl/welcome.html'/>">  send  </a>
</BODY>
</HTML>

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- JSTL url 태그는 파라미터가 포함된 URL문자열을 생성해주기 때문에
  링크에 사용될 URL을 생성할 때 유용하다
 --%>
<c:set var="page" value="7" />
<c:url value="readBoard.jsp" var="linkURL">
 <c:param name="page" value="${page}" />
</c:url>
<!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=EUC-KR">
<title>JSTL URL example</title>
</head>
<body><br/><br/><center>
<a href="${linkURL}">여기를 클릭</a>
</center>
</body>
</html>


<c:redirect>
<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>
<c:redirect url="http://localhost/jstl/welcome.html" />
</BODY>
</HTML>

<c:redirect> <c:param>
<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>
<c:redirect  url="http://localhost/jstl/sample.jsp" >
 <c:param name="name1" value="SAM"/>
</c:redirect>
<!-- sample.jsp에서는 다음과 같이 파라미터에 접근할 수 있다.-->
<c:out value="${param.name1}"/>
</BODY>
</HTML>

sample.jsp
<%@ page contentType="text/html;charset=KSC5601" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>
JSTL  welcomes <br> 
<c:out   value="${param.name1}"   /> 
<br> 
JSP Expression welcomes 
<%=request.getParameter("name1") %>
</BODY>
</HTML>


<c:catch> 페이지 처리 중에 발생한 오류를 저장하는 변수를 설정할 수 있다. 그 변수를 사용하면 이 후에 오류의 발생 여부 및 오류 메시지 등을 확인/출력할 수 있다.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<c:catch var="coercionError">

The value of myInteger is:<c:out value="${param.num}"/>

Perform a multiplication operation to show that the type is correct:<c:out value="${param.num *2}"/>

</c:catch >

<c:if test="${not empty coercionError}">

<b>The value of month is supposed to be a number.</b>

Here 's more information on the error:

<br><font color="#FF0000"><c:out value="${coercionError}"/>

</font>

</c:if>
</body>
</html>



<fmt:requestEncoding> <% request.setCharacterEncoding="euc-kr" %> 대신 사용할 수 있는 JSTL 태그

<%-- jstl_requestEncoding.jsp --%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:requestEncoding value="euc-kr"/>
<html>
<head>
 <title>JSTL fmt:requestEncoding example</title>
</head>
<body>
 전 페이지에서 전달된 파라미터:<c:out value="${param.msg}"/>
 <form method="post" action="jstl_requestEncoding.jsp">
  한글입력:<input type="text" name="msg">
  <input type="submit" value="확인">
 </form>
</body>
</html>


<fmt:formatDate> 날짜(java.util.Date)를 출력할 때 그 포맷을 지정하여 출력할 수 있다

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
  <head>
    <title>Format Date</title>
  </head>

  <body>
    <c:set var="now" value="<%=new java.util.Date()%>" />

    <table border="1" cellpadding="0" cellspacing="0"
    style="border-collapse: collapse" bordercolor="#111111"
    width="63%" id="AutoNumber2">
      <tr>
        <td width="100%" colspan="2" bgcolor="#0000FF">
          <p align="center">
            <b>
              <font color="#FFFFFF" size="4">Formatting:
              <fmt:formatDate value="${now}" type="both"  timeStyle="long" dateStyle="long" />
              </font>
            </b>
          </p>
        </td>
      </tr>

      <tr>
        <td width="51%">formatDate type="time"</td>

        <td width="49%">
          <fmt:formatDate type="time" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">type="date"</td>

        <td width="49%">
          <fmt:formatDate type="date" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">type="both"</td>

        <td width="49%">
          <fmt:formatDate type="both" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">type="both" dateStyle="default" timeStyle="default"</td>

        <td width="49%">
          <fmt:formatDate type="both" dateStyle="default" timeStyle="default" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">type="both" dateStyle="short" timeStyle="short"</td>

        <td width="49%">
          <fmt:formatDate type="both" dateStyle="short" timeStyle="short" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">type="both" dateStyle="medium" timeStyle="medium"</td>

        <td width="49%">
          <fmt:formatDate type="both" dateStyle="medium" timeStyle="medium" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">type="both" dateStyle="long" timeStyle="long"</td>

        <td width="49%">
          <fmt:formatDate type="both" dateStyle="long" timeStyle="long" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">type="both" dateStyle="full" timeStyle="full"</td>

        <td width="49%">
          <fmt:formatDate type="both" dateStyle="full" timeStyle="full" value="${now}" />
        </td>
      </tr>

      <tr>
        <td width="51%">pattern="yyyy-MM-dd"</td>

        <td width="49%">
          <fmt:formatDate pattern="yyyy-MM-dd" value="${now}" />
        </td>
      </tr>
    </table>
  </body>
</html>


출력결과 화면

Formatting: 2010년 11월 25일 (목) 오후 12시 45분 20초

formatDate type="time" 오후 12:45:20
type="date" 2010. 11. 25
type="both" 2010. 11. 25 오후 12:45:20
type="both" dateStyle="default" timeStyle="default" 2010. 11. 25 오후 12:45:20
type="both" dateStyle="short" timeStyle="short" 10. 11. 25 오후 12:45
type="both" dateStyle="medium" timeStyle="medium" 2010. 11. 25 오후 12:45:20
type="both" dateStyle="long" timeStyle="long" 2010년 11월 25일 (목) 오후 12시 45분 20초
type="both" dateStyle="full" timeStyle="full" 2010년 11월 25일 목요일 오후 12시 45분 20초 KST
pattern="yyyy-MM-dd" 2010-11-25



<fmt:formatNumber> 문자열로 표현된 숫자를 변환하거나 통화, 퍼센트 기호를 함께 출력해주는 기능

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<head><title>JSTL formatNumber</title></head>
<body><br/><br/><center>

 <H2>Number Format Example </H2>
 Formatting <B>123.4</B> becomes : <fmt:formatNumber value="123.4" type="NUMBER"  minFractionDigits="3" /><BR>
 <HR>
 <H2>Currency Format Example </H2>
 <c:set var="salary" value="125000" />
 Salary =<c:out value="${salary}"/><BR>
 
 <fmt:setLocale value="ko_KR"/>
 Formatting salary with Locale <B>ko_KR</B> becomes : <fmt:formatNumber type="CURRENCY" value="${salary}" /><BR>

 <c:set var="per" value="0.93"/>
 <fmt:setLocale value="ko_KR"/>
 Formatting per with Locale <B>ko_KR</B> becomes : <fmt:formatNumber type="PERCENT" value="${per}" /><BR>
</center>
</body>
</html>





<fmt:parseNumber> 문자열, 금액, 페센트 등에 포함된 문자열이 있을 경우에 숫자로 parsing 해 주는 기능

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>
  <title>JSTL fmt:parseNumber Tag</title>
</head>
<body>
<h3>Number Parsing:1250003.350</h3>
<c:set var="balance" value="1250003.350" />

<fmt:parseNumber var="i" type="number" value="${balance}" />
<p>Parsed Number (1) : <c:out value="${i}" /></p>

<fmt:parseNumber var="i" integerOnly="true" type="number" value="${balance}" />
<p>Parsed Number (2) : <c:out value="${i}" /></p>

<fmt:parseNumber var="i" type="currency" value="$10.00" parseLocale="en_US"/>
<p>Parsed Number (3) : <c:out value="${i}" /></p>

<fmt:parseNumber var="i" type="currency" value="1,000원" parseLocale="ko_KR" pattern="###,###,###원"/>
<p>Parsed Number (4) : <c:out value="${i}" /></p>

<fmt:parseNumber var="i" type="currency" value="1,000원" parseLocale="ko_KR" pattern="000,000,000원"/>
<p>Parsed Number (5) : <c:out value="${i}" /></p>

<fmt:parseNumber var="i" type="percent" value="100%" parseLocale="en_US"/>
<p>Parsed Number (6) : <c:out value="${i}" /></p>

</body>
</html>





<fmt:parseDate> 문자열 형태로 된 날짜를 Date객체로 변환해주는 기능

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<c:set var="usDateString">4/1/03 7:03 PM</c:set>
<fmt:parseDate value="${usDateString}" parseLocale="en_US"
        type="both" dateStyle="short" timeStyle="short"
        var="usDate"/>

<c:set var="gbDateString">4/1/03 19:03</c:set>
<fmt:parseDate value="${gbDateString}" parseLocale="en_GB"
        type="both" dateStyle="short" timeStyle="short"
        var="gbDate"/>
       
<c:set var="koDateString">06. 04. 10 오후 7:03</c:set>
<fmt:parseDate value="${koDateString}" parseLocale="ko_KR"
       type="both" dateStyle="short" timeStyle="short"
       var="koDate"/>

<ul>
<li> Parsing <c:out value="${usDateString}"/> against the
U.S. English
     locale yields a date of <c:out value="${usDate}"/>.</li>

<li> Parsing <c:out value="${gbDateString}"/> against the
British English
     locale yields a date of <c:out value="${gbDate}"/>.</li>
    
<li> Parsing <c:out value="${koDateString}"/> against the
Korean Korea
     locale yields a date of <c:out value="${koDate}"/>.</li>
</ul>

</body>
</html>


게시판의 리스트 페이지에 JSTL, EL을 적용한 예 ( JSTL적용전의 코드는 주석처리한 부분을 참조하세요 )

<%@page import="java.util.ArrayList"%>
<%@page import="board.*"%>

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="f" uri="
http://java.sun.com/jsp/jstl/functions" %>

<jsp:useBean id="pageUtil" class="board.PageUtilBean" scope="page">
  <c:set target="${pageUtil}" property="currPage" value="${param.pg}"/>
  <c:set target="${pageUtil}" property="numsPerPage" value="${3}"/>
<%--<jsp:setProperty name="pageUtil" property="currPage" param="pg"/>
   <jsp:setProperty name="pageUtil" property="numsPerPage" value="2"/> --%>
</jsp:useBean>
<%-- <% 
 ArrayList<BoardDTO> list = (ArrayList<BoardDTO>)request.getAttribute("list");
%> --%>
<!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=EUC-KR">
<title>게시판 글 리스트</title>
<style>
 .title {
  background-color: rgb(255,215,255);
  border-bottom: 1px double gray;
 }
 tr {height:2em; }
 td {border-bottom: dotted;}
 .coloredRow {background-color:rgb(255,215,255); }
 a:link { text-decoration: none; }
 a:visited { text-decoration: none; }
 a:hover { color:red; }
</style>
</head>
<body><center>
<table width="500">
<caption><h2>게시판 글 리스트</h2></caption>
<tr><td colspan="3" align="right">
   ${pageUtil.currPage}/${pageUtil.totalPages}
   <%--<jsp:getProperty name="pageUtil" property="currPage"/>/
     <jsp:getProperty name="pageUtil" property="totalPages"/> --%>
</td></tr>
<tr class="title"><th>글 번호</th><th>글 제목</th><th>내 용</th></tr>
<c:forEach var="b" items="${list}" varStatus="status">
 <c:set var="style" value="${''}"/>
 <c:if test="${status.index%2==1}">
  <c:set var="style" value="${'coloredRow'}"/>
 </c:if>
 <c:set var="subject" value="${f:replace(b.subject,' ','&nbsp;')}"/>
 <tr class="${style}"
   onmouseover="oldBg=this.style.backgroundColor;style.backgroundColor='rgb(187,233,255)'"
   onmouseout="this.style.backgroundColor=oldBg;">
  <td>${b.num}</td>
  <td align="left" style="width:350px;">
   <a href="BoardServlet?cmd=read&num=${b.num}">${subject}</a>
  </td>
  <td>${b.author}</td>
 </tr>
</c:forEach>
<%-- <%
 for(int i=0;i<list.size();i++){
  BoardDTO dto = list.get(i);
  String style = null;
  if(i%2==1) style="class=\"coloredRow\"";
  else style="";
  int num = dto.getNum();
  String subject = dto.getSubject().replaceAll(" ", "&nbsp;");
  %>
  <tr <%=style%>
   onmouseover="oldBg=this.style.backgroundColor;style.backgroundColor='rgb(187,233,255)'"
   onmouseout="this.style.backgroundColor=oldBg;">
   <td><%=num%></td>
   <td align="left" style="width:350px;">
    <a href="BoardServlet?cmd=read&num=<%=num%>"><%=subject%></a>
   </td>
   <td><%=dto.getAuthor()%></td>
  </tr>
<% }
%> --%>
</table>
<hr width="50%"/>

${pageUtil.navStr}
<%-- <jsp:getProperty property="navStr" name="pageUtil"/> --%>

<hr width="50%"/>

[<a href="inputForm.jsp">글쓰기</a>]
</center>

</body>
</html>