JSTL
JSTL은 Java Server Page Standard Tag Library의 약자로 JSP에서 사용하는 태그 라이브러리를 공통으로 사용하기 위해 정해진 표준이다.
즉 표준화된 태그 라이브러리 .
우리가 시스템 을 개발할때 개발자들이 공통으로 많이 사용하는 기능이 있다. JSTL은 이러한 공토응로 사용되는 기능들을 미리 구현해놓은 커스텀 태그를 만들어 사용할 필요없이 JSTL를 그대로 사용하면 된다.
표준 커스텀태그 라이브러리인 JSTL에서 제공하는 JSTL태그를 알아보고 활용
JSTL 개요와 설치
1. 개요
버전 |
JSTL 버전 |
요구사항 |
Standard 1.2.3 |
JSTL 1.2 |
Servlet 2.5,JavaServer Pages 2.1 |
Standard 1.1 |
JSTL 1.1 |
Servlet 2.4, JavaServer Page 2.0 |
Standard 1,0 |
JSTL 1,0 |
Servlet 2.3, JavaServer Page 1.2 |
JSTL에서는
Core, Formatting,SQL,XML ,Functions 등 5개의 태그 라이브러리를 제공하고 있다.
각 태그 라이브러리는 기능별로 분류되어있다.
core는 프로그램 개발시 사용되는 기본적인 기능들
formatting은 날짜, 시간에 관한 형식을 처리하는 기능,
sql은 데이터베이스 작업에 관한 기능들을 수행하는 태그들이 포함
XML은 XML을 지원하는 태그
function은 여러가지 함수기능을 제공
설치
Core
[1] <c:set>
1.value attribute를 사용하여 지정
2.value attribute를 사용하여 대상 객체의 값을 지정
[2]<c:out>
[3] <c:remove>
[4]<c:catch>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | <%@page import="com.edu.beans.BookBean"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="name" value="Amy"/> <c:out value="${name }"/><br> <c:remove var="name"/> <c:out value="${name}"/><br> <% BookBean book = new BookBean("The Seceret","Byrne","Atira Books"); request.setAttribute("bookOne", book); %> <c:set var="title" value="${bookOne.title}"/> <c:out value="${title}"/><br> <c:set var="author" value="<%=book.getAuthor() %>"/> <c:out value="${author}"/> <hr> <c:set var="name">Tobey</c:set> <c:out value="${name}"/><br> <% BookBean book2 = new BookBean("The Lecture","Randy","hyperion"); request.setAttribute("bookTwo", book2); %> <c:set var="title" value="${bookTwo.title}"/> <c:out value="${title}"/> <c:set var="author" value="<%=book2.getAuthor() %>"/><br> <c:out value="${author}"/> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> </body> </html> | cs |
The Seceret
Byrne
Tobey
The Lecture
Randy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <%@page import="com.edu.beans.BookBean"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% BookBean book = new BookBean(); %><!-- //BookBean 객체 생성 --> <!-- 빈 객체에 값을 넣음 --> <c:set target="<%=book%>" property="title" value="The Secret" /> <%=book.getTitle()%><br> <c:set var="b" value="<%=book%>" /><!-- 타겟으로 지정할 객체를 지정해서 b라고 이름지음 --> <c:set target="${b}" property="author" value="Byrne, Rhonda" /><!-- 그객체의 저자에 값을 입력 --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> ${b.author} <br> ${b.title } </body> </html> | cs |
The Secret
Byrne, Rhonda The Secret
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String str = request.getParameter("msg"); %> <c:catch var="e"><!-- 오류발생시 실행하는태그 --> <% if(str.equals("add")){/* 전해들어온 메시지가 add와 갑으면 실행 */ out.print(str); } %> </c:catch> <c:out value="${e}"/><!-- 오류 발생 객체를 출력해준다. --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> </body> </html> | cs |
조건액션
[1] <c:if>
[2] <c:choose>
[3] <c:when>
[4]<c:otherwise>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <c:set var="num" value="${95}"/> 점수는 <c:out value="${num}"/> <c:if test="${num>60 }"> 합격입니다. </c:if> <c:choose> <c:when test="${num>=90 }">A학점입니다.</c:when> <c:when test="${num>=80 }">B학점입니다.</c:when> <c:when test="${num>=70 }">C학점입니다.</c:when> <c:when test="${num>=60 }">D학점입니다.</c:when> <c:otherwise>F학점입니다.</c:otherwise> </c:choose> <br> </body> </html> | cs |
결과
점수는 95 합격입니다. A학점입니다.
반복 액션
[1]<c:forEach>
items : 반복실행할 데이터가 저장된 배열 Collections 객체를 지정한다. 지정된 데이터 요소수 만큼 반복실행한다.
var : items에 지정된 요소 수만큼 반복 실행 될 때 각 요소가 저장되는 변수 이름을 지정한다.
begin: 반복실행 횟수의 시작값을 지정한다.
end : 반복 실행 횟수의 끝값을 지정한다.
step : 반복실행 횟수의 증감값을 지정한다.
[2] <c:forTokens>
items : 분리하고자 하는 문자열
delims: 문자열을 분리할 기호
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <%@page import="com.edu.beans.BookBean"%> <%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% ArrayList<BookBean>bookList = new ArrayList<BookBean>(); bookList.add(new BookBean("seceret","b","a")); bookList.add(new BookBean("Lecture","r","h")); String [] bookCode ={"소설","역사","인문","정치","미술","종교","여행","과학","만화","건강"}; %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <c:set var="list" value="<%=bookList%>"/> <c:forEach items="${list}" var="item"> ${item.title}/${item.author}/${item.publisher}<br> </c:forEach> <hr> <c:set var="code" value="<%=bookCode%>"/> <c:forEach var="item" items="${code}"> <c:out value="${item}"></c:out> </c:forEach> <br> <hr> <c:forEach var="i" begin="2" end="9"> <c:forEach var="j" begin="2" end="9"> ${i}*${j} = ${i*j}<br> </c:forEach> <hr> </c:forEach> <hr> <c:forEach var="k" begin="1" end="10" step="2"> ${k} </c:forEach> <hr> <c:forTokens items="소설/역사/인문/정치/미술/종료/여행/과학/만화/건강" delims="/" var="token"> ${token } </c:forTokens> </body> </html> | cs |
결과
seceret/b/a
Lecture/r/h
소설 역사 인문 정치 미술 종교 여행 과학 만화 건강
2*2 = 4
2*3 = 6
2*4 = 8
2*5 = 10
2*6 = 12
2*7 = 14
2*8 = 16
2*9 = 18
3*2 = 6
3*3 = 9
3*4 = 12
3*5 = 15
3*6 = 18
3*7 = 21
3*8 = 24
3*9 = 27
4*2 = 8
4*3 = 12
4*4 = 16
4*5 = 20
4*6 = 24
4*7 = 28
4*8 = 32
4*9 = 36
5*2 = 10
5*3 = 15
5*4 = 20
5*5 = 25
5*6 = 30
5*7 = 35
5*8 = 40
5*9 = 45
6*2 = 12
6*3 = 18
6*4 = 24
6*5 = 30
6*6 = 36
6*7 = 42
6*8 = 48
6*9 = 54
7*2 = 14
7*3 = 21
7*4 = 28
7*5 = 35
7*6 = 42
7*7 = 49
7*8 = 56
7*9 = 63
8*2 = 16
8*3 = 24
8*4 = 32
8*5 = 40
8*6 = 48
8*7 = 56
8*8 = 64
8*9 = 72
9*2 = 18
9*3 = 27
9*4 = 36
9*5 = 45
9*6 = 54
9*7 = 63
9*8 = 72
9*9 = 81
1 3 5 7 9
소설 역사 인문 정치 미술 종료 여행 과학 만화 건강
URL액션
[1] <c:import>
<c:imprort url="url" [context="context"] [var="varname"] [scope=""] [charEncoding=""]>
<c:param> tag를 하위 tag로 사용하는 body 내용
</c:import>
url : 현재페이지에 결과를 삽입할 페이지의 URL을 지정한다.
var : url 속성에 지정한 페이지의 결과를 저장할 변수를 지정한다.
[2]<c:url>
[3] <c:param>
[4] <c:redirect>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:import url="ex5.jsp" var="url"/> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> === import 파일 내용 === <p>${url}</p> </body> </html> | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <c:url value="ex8.jsp" var="page"> <c:param value="guest" name="id"/> <c:param value="1004" name="pwd"/> </c:url> <c:redirect url="${page}"/> </body> </html> | cs |
|
V
1 2 3 4 5 6 7 8 9 10 11 12 13 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h3>ex8.jsp</h3> ${param.id }/${param.pwd } </body> </html> | cs |
Formatting
[1] 유니코드 변환
1 2 | id = 손님 greeting = 안녕하세요 | cs |
1 2 | id = guest greeting = Hello~~ | cs |
- Locale 설정 : <fmt:setLocale>, <ftm:requestEncoding>
- 메시지 처리 : <fmt:bundle>, <fmt:message>(<fmt:param>), <fmt:setBundle>
- 숫자 날짜 형식 : <fmt:formatNumber>, <fmt:formatDate>, <fmt:parseDate>, <fmt:parseNumber>, <fmt:setTimeZone>, <fmt:timeZone>
i18n 액션
- value 속성 : 로케일 값이 들어가며, 두 글자로 된 언어 코드를 반드시 지정해 주어야 한다. 언어 코드와 국가 코드는 "-","_" 로 연결한다. 한글의 경우 ko_kr로 지정할 수 있다.
- variant 속성 : 다양한 프라우저의 스펙 등을 기술한다.
- value 속성 : 값에는 생성할 URL이 들어간다.
- scope 속성 : var 속성에서 지정한 변수의 공유 범위를 나타내는 것으로 생략 시 page가 기본값이다.
- basename 속성 : properties 파일명이 기술된다. properties 파일은 보통 WEB-INF/classes 폴더 안에 위치하며 디렉터리의 깊이에 따라서 패키지 형식의 이름을 가진다. testBundle.properties 파일이 bundle 폴더 안에 있다면 basename의 속성값은 bundle.testBundle로 기술한다. 로케일(locale)이 ko 라면 testBundle_ko.properties 파일을 읽어오게 되며, locale 이 맞지 않는 경우에는 testBundle.properties 처럼 언어 코드가 붙지 않은 파일을 읽어온다.
- prefix 속성 : key 이름이 공통적인 부분을 지정해서 body에서 표현되는 key를 단축 시킨다.
- key 속성 : 읽어올 메시지의 key 값이 기술된다.
- bundle 속성 : setBundle 태그를 사용해서 로딩한 번들을 읽어올 때 사용한다. var 속성은 메시지를 저장할 변수명을 기술한다.
- scope 속성 : 변수가 저장된는 공유 범위를 지정한다.
- basename 속성 : properties 파일명이 기술된다.
- var 속성 : 메시지를 저장할 변수명을 기술한다.
- scope 속성 : 변수가 저장되는 공유 범위를 지정한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <fmt:requestEncoding value="UTF-8"/> Parameter : ${param.name}<br> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="ex9.jsp" method="post"> 이름 : <input type="text" name="name"> <input type="submit" value="전송"> </form> </body> </html> | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <fmt:bundle basename="com.edu.bundle.msg"> <fmt:message key="id"/> <fmt:message key="greeting"/> </fmt:bundle> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> </body> </html> | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <fmt:setLocale value="en"/> <fmt:bundle basename="com.edu.bundle.msg"> <fmt:message key="id"/> <fmt:message key="greeting"/> </fmt:bundle> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> </body> </html> | cs |
1 2 3 | id = 손님 greeting = 안녕하세요 name = {0}님 환영합니다. | cs |
1 2 3 | id = guest greeting = Hello~~ name =welcome ! {0} | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <fmt:setBundle basename="com.edu.bundle.msg"/> <fmt:message var="name" key="name"> <fmt:param>Amy</fmt:param> </fmt:message> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> ${name} </body> </html> | cs |
- value 속성 : Number로 형식화될 수치 지정
- type 속성 : 숫자, 통화, 퍼센트({number|currency|percent})중 어느 것으로 표시할 것인지 지정
- pattern 속성 : 사용자가 지정한 형식 패턴 지정
- currencyCode 속성 : ISO 4217 통화 코드 지정. 통화 형식일 때만 적용(type="currency")
- currencySymbol 속성 : 통화 기호 지정. 통화 형식일 때만 적용(type="currency")
- groupingUsed 속성 : 출력에 그룹 분리 기호를 포함할지 여부를 지정
- maxIntegerDigits 속성 : 출력에서 integer 최대 자릿수 지정
- minIntegerDigits 속성 : 출력에서 integer 최소 자릿수 지정
- maxFractionDigits 속성 : 출력에서 소수점 이하 최대 자릿수 지정
- minFractionDigits 속성 : 출력에서 소수점 이하 최소 자릿수 지정
- var 속성 : 출력 결과 문자열을 담는 scope에 해당하는 변수명 지정
- scope 속성 : var의 scope 지정
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <c:set var="val" value="123456.789"/><br> <fmt:formatNumber type="currency" value="${val}"/><br> <fmt:formatNumber type="number" maxIntegerDigits="3" value="${val}"/><br> <fmt:formatNumber type="number" maxFractionDigits="3" value="${val}" /><br> <fmt:formatNumber type="number" groupingUsed="flase" value="${val}" /><br> <fmt:formatNumber type="percent" maxIntegerDigits="3" value="${val}"/><br> <fmt:formatNumber type="percent" minFractionDigits="10" value="${val}" /><br> <fmt:formatNumber type="percent" minIntegerDigits="3" value="${val}"/><br> <fmt:formatNumber type="number" pattern="###.###E0" value="${val}"/><br> <p> Currency in USA : <fmt:setLocale value="en_US"/> <fmt:formatNumber value="${val}" type="currency"/> </p> <fmt:parseNumber value="1,234.56" pattern="0,000.000" var="num1"/> <fmt:parseNumber value="123" var="num2"/> ${num1+num2 } </body> </html> | cs |
₩123,457
456.789
123,456.789
123456.789
679%
12,345,678.9000000000%
12,345,679%
123.457E3
Currency in USA : $123,456.79
1357.56- value 속성 : Number를 파싱할 수치 지정
- type 속성 : 숫자, 통화, 퍼센트({number|currency|percent})중 어느 것으로 표시할 지를 지정
- pattern 속성 : 사용자가 지정한 형식 패턴 지정
- parseLocale 속성 : 파싱 작업의 기본 형식 패턴(숫자, 통화, 퍼센트 각각)을 제공하는 Locale로 지정.
- integerOnly속성 : 주어진 값에서 integer 부분만 파싱할지 여부를 지정
- var 속성 : 파싱 결과를 저장할 scope에 해당하는 변수명 지정
- scope 속성: var의 scope 지정
- value 속성 : 형식화될 Date 와 time 지정
- type 속성 : 형식화할 데이터가 시간, 날짜, 모두 {time|date|both}의 세 형식중 하나를 지정
- dateStyle 속성 : type 속성을 생략하거나 date 또는 both일 때 사용하는 것으로 미리 정의된 날짜 형식 지정
- timeStyle 속성 : type 속성이 time 또는 both일 때 사용하는 것으로 미리 정의된 시간 형식 지정
- pattern 속성 : 사용자 지정 형식 스타일 지정
- timeZone 속성 : java.util.TimeZone 형식으로 된 시간에 나타날 타임 존 지정
- var 속성 : 출력 결과를 문자열로 담는 scope에 해당하는 변수명 지정
- scope 속성 : var의 scope 지정
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <c:set var="now" value="<%=new java.util.Date() %>"/> <fmt:formatDate type="time" value="${now}"/><br> <fmt:formatDate type="date" value="${now}"/><br> <fmt:formatDate type="both" value="${now}"/><br> <fmt:formatDate type="both" dateStyle="short" timeStyle="short" value="${now}"/><br> <fmt:formatDate type="both" dateStyle="medium" timeStyle="medium" value="${now}"/><br> <fmt:formatDate type="both" dateStyle="long" timeStyle="long" value="${now}"/><br> <fmt:formatDate pattern="yyyy-MM-dd" value="${now}"/><br> <fmt:parseDate value="2016-12-24 09:03:23" pattern="yyyy-MM-dd HH:mm:ss" var="date" /> <p>${date}</p> </body> </html> | cs |
2019. 3. 8
2019. 3. 8 오전 11:50:19
19. 3. 8 오전 11:50
2019. 3. 8 오전 11:50:19
2019년 3월 8일 (금) 오전 11시 50분 19초
2019-03-08
Sat Dec 24 09:03:23 KST 2016
- value 속성 : 파싱할 Date 와 time 지정
- type 속성 : 파싱할 데이터가 시간, 날짜, 모두의 세 형식 중 하나를 지정.
- dateStyle 속성 : type 속성이 생략 또는 date 또는 both일 때 사용하는 것으로 미리 정의된 날짜 형식 지정.
- timeStyle 속성 : type 속성이 time 또는 both일 때 사용하는 것으로 미리 정의된 시간 형식 지정.
- pattern 속성 : 사용자 지정 형식 스타일 지정.
- timeZone 속성 : 형식화 시간에 나타날 타임 존 지정.
- parseLocale 속성 : 파싱하는 동안 적용될 미리 정의된 형식 스타일의 Locale 지정.
- var 속성 : 파싱 결과(java.util.Date)를 담는 scope에 해당하는 변수명 지정
- scope 속성 : var의 scope 지정