1. JSTL 이란?
- JSP Standard Tag Library : 널리 사용되는 커스텀 태그를 표준으로 만든 태그 라이브러리
- JSP 페이지에서 많이 사용되는 논리적인 판단, 반복 처리, 포맷 처리를 위한 커스텀 태그를
표준으로 만들어서 정의한다.
* JSTL은 가독성이 좋아지고 코드가 간결해진다는 장점을 가지고 있다.
* 널리 사용하는 태그들을 표준으로 만들어서 라이브러리화 시킨것을 JSTL 이라고 한다.
* 커스텀태그로 직접 태그를 만들 수 있다! 하지만 우리는 커스텀태그(16장) 안배울것임
<%-- 스크립트 코드(스크립트릿, 표현식)과 HTML 코드 --%>
<%
if (list.size() > 0) {
for (int i=0; i<list.size(); i++) {
Data data = (Data) list.get(i);
%>
<%= data.getTitle() %>
<!-- 원래 스크립트 코드로는 문서를 출력하려면 위처럼 코드를 끊고
<%= data.getTitle( ) %> 이렇게 출력하라는 코드를 적어줘야한다. -->
...
<%
}
} else {
%>
데이터가 없습니다.
<%
}
%>
<%-- JSTL 태그 --%>
<ctag:if test="!empty ${list}"> <!-- if 라는 액션을 준다 는 의미 여기에 접두어에 c 가 있다는 것이 코어 라이브러리에서 제공하는 것이라는 걸 뜻한다. -->
<ctag:foreach varName="data" list="${list}">
${data.title} <!-- 위의 <%= data.getTitle( ) %> 코드와 같은 것 -->
</ctag:foreach>
</ctag:if>
<ctag:if test="empty ${list}">
데이터가 없습니다.
</ctag>
1-1. JSTL이 제공하는 태그의 종류
1-2. JSTL 라이브러리 받기
- JSTL을 사용하려면 JSTL 1.2 버전을 구현한 jar 파일을 다운로드해야 한다.
다운로드한 JSTL.jar 파일을 WEB-INF/lib 디렉터리에 복사한다.
• http://repo1.maven.org/maven2/jstl/jstl/1.2/jstl-1.2.jar
* c 태그를 사용하기 위해서는 먼저 아래의 사진처럼 저 위치에 jstl-1.2.jar 라이브러리를 넣어줘야한다.
*그 다음 c 태그를 사용하기 위해서는 아래의 코드를 jsp 파일의 코드 맨 위에 적어줘야한다.
-> 다른 방법은 Apache Maven 파일 (pom.xml)에 아래와 같이 코드를 추가해 놓는다.
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
2. 코어 태그
- 코어 태그 라이브러리를 사용하려면 JSP페이지에 다음과 같이 taglib 디렉티브를 추가해야 한다.
* c 태그를 사용하기 위해서는 아래 코드를 코드 맨 위에 꼭 적어줘야한다!!
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2-1. 변수 지원 태그
(1) < c : set > 태그
- EL 변수를 설정한다.
- < c : set > 태그는 객체의 프로퍼티 값을 설정한다.
<%-- 기본형 --%>
<c:set var="변수명" value="값" [scope="영역"] />
<c:set target="대상" property="프로퍼티이름" value="값" />
<%-- 예시 --%>
<c:set var="member" value="<%= member %>" />
<c:set target="memeber" property="name" value="홍길동" />
(2) < c : remove > 태그
- 변수 삭제
<c:remove var="varName" [scope="영역"] />
<c:set var="name" value="최범균" scope="request" />
<c:set var="name" value="최범균" scope="session" />
<c:remove var="name" />
2-2. 흐름 제어 태그
(1) < c : if 태그 >
- 조건이 true일 경우 몸체 내용 실행
<c:if test="조건">
...
</c:if>
<!-- use_if_tag.jsp 코드 -->
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>if 태그</title>
</head>
<body>
<c:if test="true">
무조건 수행<br>
</c:if>
<c:if test="${param.name == 'bk'}">
name 파라미터의 값이 ${param.name} 입니다.<br>
</c:if>
<c:if test="${18 < param.age}">
당신의 나이는 18세 이상입니다.
</c:if>
</body>
</html>
(2) <c:choose>, <c:when> , <c:otherwise> 태그
- switch - case - default 와 동일
<c:choose>
<c:when test="${member.level == 'trial'}">
...
</c:when>
<c:when test="${member.level == 'regular'}">
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>
<!--use_choose_tag.jsp 코드 -->
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>choose 태그</title>
</head>
<body>
<!-- <%
String name = "bk";
switch(name) {
case "bk" :
out.println("당신의 이름은 bk입니다.");
break;
default:
// ....
}
%>-->
<!-- choose 는 switch 와 비슷한 아이이다. -->
<ul>
<c:choose>
<c:when test="${param.name == 'bk'}">
<li>당신의 이름은 ${param.name} 입니다.
</c:when>
<c:when test="${param.age > 20}">
<li>당신은 20세 이상입니다.
</c:when>
<c:otherwise>
<li>당신은 'bk'가 아니고 20세 이상이 아닙니다.
</c:otherwise>
</c:choose>
</ul>
</body>
</html>
(3) <c:forEach> 태그
- 집합이나 콜렉션 데이터 사용
- 특정 회수 반복
- varStatus 속성 : 루프 정보를 담는 객체를 저장할 변수명을 값으로 갖는다.
- index : 루프 실행에서 현재 인덱스, count - 루프 실행 회수
- begin : begin 속성 값, end - end 속성 값, step
- step 속성 값 - first : 현재 실행이 첫 번째 실행인 경우 true
- last : 현재 실행이 루프의 마지막 실행인 경우 true
- current : 콜렉션 중 현재 루프에서 사용할 객체
<c:forEach var="변수" items="아이템">
… ${변수사용} ...
</c:forEach>
<c:forEach var="i" begin="1" end="10" [step="값"]>
${i} 사용
</c:forEach>
<c:forEach var="item" items="<%= someItemList %>" varStatus="status">
${status.index + 1} 번째 항목 : ${item.name}
</c:forEach>
<!-- use_foreach_tag.jsp 코드 -->
<%@ page contentType="text/html; charset=utf-8"%>
<%@ page import="java.util.HashMap"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
HashMap<String, Object> mapData = new HashMap<String, Object>();
mapData.put("name", "최범균");
mapData.put("today", new java.util.Date());
%>
<c:set var="intArray" value="<%=new int[] { 1, 2, 3, 4, 5 }%>" />
<!-- 위의 코드는 intArray 변수에 int형 배열 {1,2,3,4,5}를 넣는다는 것이다. -->
<c:set var="map" value="<%=mapData%>" />
<html>
<head>
<title>forEach 태그</title>
</head>
<body>
<h4>1부터 100까지 홀수의 합</h4>
<c:set var="sum" value="0" />
<c:forEach var="i" begin="1" end="100" step="2">
<c:set var="sum" value="${sum + i}" />
</c:forEach>
결과 = ${sum}
<h4>구구단: 4단</h4>
<ul>
<c:forEach var="i" begin="1" end="9">
<li>4 * ${i} = ${4 * i}
</c:forEach>
</ul>
<h4>int형 배열</h4>
<c:forEach var="i" items="${intArray}" begin="2" end="4"
varStatus="status">
${status.index}-${status.count}-[${i}] <br />
</c:forEach>
<h4>Map</h4>
<c:forEach var="i" items="${map}">
${i.key} = ${i.value}<br>
</c:forEach>
</body>
</html>
(4) < c : forTokens > 태그
- java.util.StringTokenizer 클래스와 같은 기능을 제공하는 태그이다.
<c:forTokens var="token" items="문자열" delims="구분자">
${token}의 사용
</c:forTokens>
<!-- use_fortoken_tag.jsp 코드 -->
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>forTokens 태그</title>
</head>
<body>
콤마와 점을 구분자로 사용:
<br>
<!-- token 이라는 변수에 items 값들을 넣는다. 이때 구분자(delims)는 , 와 . 두개 -->
<c:forTokens var="token" items="빨강색,주황색.노란색.초록색,파랑색,남색.보라색" delims=",.">
${token}
</c:forTokens>
</body>
</html>
2-3 URL 처리 태그
(1) < c : url > 태그
- 절대 URL과 상대 URL을 알맞게 생성
<c:url value="URL" [var="varName"] [scope="영역"]>
<c:param name="이름" value="값" />
</c:url>
<!-- use_url_tag.jsp 코드 -->
<%@ page contentType="text/html; charset=utf-8" session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<c:url value="http://search.daum.net/search" var="searchUrl">
<c:param name="w" value="blog" />
<c:param name="q" value="공원" />
</c:url>
<ul>
<li>${searchUrl}</li>
<li><c:url value="/use_if_tag.jsp" /></li>
<li><c:url value="./use_if_tag.jsp" /></li>
</ul>
</body>
</html>
3. 국제화 태그
3-1. 로케일 지정 태그
- < fmt : setLocale value="언어코드" scope="범위" />
- 국제화 태그가 Accept-Language 헤더에서 지정한 언어가 아닌 다른 언어를 사용하도록 지정하는 기능
- < fmt : requestEncoding value="캐릭터셋" />
- 요청 파라미터의 캐릭터 인코딩을 지정
- request.setCharacterEncoding("캐릭터셋")과 동일
<%@ tablib prefix="fmt" url="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setLocale value="ko" scope="request" />
<fmt:requestEncoding value="utf-8" />
<%-- 위 코드는 다음 코드와 동일하다. --%>
<%
request.setCharacterEncoding("utf-8");
%>
3-2. 예제로 사용할 리소스 번들
<!-- [ Java Resources > src > resource > message.properties 코드 ] -->
TITLE = MadVirus's Learning JSP 2.3
GREETING = HI! I'm BK
VISITOR = Your ID is {0}.
<!-- [ Java Resources > src > resource > message_ko.properties.src 코드 ] -->
TITLE = 최범균의 JSP 2.3 배우기
GREETING = 안녕하세요. 최범균입니다.
VISITOR = 당신의 아이디는 {0}입니다.
<!-- [ Java Resources > src > resource > message_ko.properties 코드 ] -->
TITLE = \ucd5c\ubc94\uade0\uc758 JSP 2.3 \ubc30\uc6b0\uae30
GREETING = \uc548\ub155\ud558\uc138\uc694. \ucd5c\ubc94\uade0\uc785\ub2c8\ub2e4.
VISITOR = \ub2f9\uc2e0\uc758 \uc544\uc774\ub514\ub294 {0}\uc785\ub2c8\ub2e4.
<!-- [ Java Resources > src > resource > message_ja.properties 코드 ] -->
TITLE = MadVirus's Learning JSP 2.3
GREETING = \u3084\u3042\uFF01\u79C1\u306F\uFF22\uFF2B\u3067\u3059
VISITOR = Your ID is {0}.
3-3. 메시지 처리 태그
- 메시지 처리 태그는 다음과 같이 세 가지가 있다.
- <fmt : bundle> : 태그 몸체에서 사용할 리소스 번들을 지정한다.
- <fmt : message> : 메시지를 출력한다.
- <fmt : setBundle> : 특정 메시지 번들을 사용할 수 있도록 로딩한다.
- < fmt : message > 태그의 메시지 읽는 순서
- bundle 속성에 지정한 리소스 번들을 사용
- < fmt : bundle > 태그에 중첩된 경우 태그에서 설정한 리소스 번들 사용
- 1과 2가 아닐 경우 기본 리소스 번들 사용. 기본 리소스 번들은 web.xml 파일에서javax.servlet.jsp.jstl.fmt.localizationContext 콘텍스트 속성을 통해서 설정 가능
<fmt:bundle basename="resource.message" [prefix="접두어"]>
<fmt:message key="GREETING" />
</fmt:bundle>
<fmt:setBundle var="message" basename="resource.message" />
...
<fmt:message bundle="${message}" key="GREETING" />
<!-- use_message_tag.jsp 코드 -->
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!-- 위의 코드를 넣어줘야 fmt 태그가 인식이 된다. -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- <fmt:setLocale value="en" /> --%>
<fmt:bundle basename="resource.message"> <!-- resource 밑에 있는 message 파일을 리소스 번들로 지정하겠다 는 의미의 코드이다. -->
<fmt:message key="TITLE" var="title" />
<html>
<head>
<title>${title}</title>
</head>
<body>
<fmt:message key="GREETING" /> <!-- GREETING을 출력하라는 코드 -->
<br>
<c:if test="${! empty param.id}">
<fmt:message key="VISITOR">
<fmt:param value="${param.id}" />
</fmt:message>
</c:if>
</body>
</html>
</fmt:bundle>
4. 함수
- JSTL이 제공하는 EL 함수
<!-- use_function.jsp코드 -->
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<html>
<head>
<title>함수 사용</title>
</head>
<body>
<c:set var="str1" value="Functions <태그>를 사용합니다. " />
<c:set var="str2" value="사용" />
<c:set var="tokens" value="1,2,3,4,5,6,7,8,9,10" />
length(str1) = ${fn:length(str1)}
<br> toUpperCase(str1) = "${fn:toUpperCase(str1)}"
<br> toLowerCase(str1) = "${fn:toLowerCase(str1)}"
<br> substring(str1, 3, 6) = "${fn:substring(str1, 3, 6)}"
<br> substringAfter(str1, str2) = "${fn:substringAfter(str1, str2)}"
<br> substringBefore(str1, str2) = "${fn:substringBefore(str1, str2)}"
<br> trim(str1) = "${fn:trim(str1)}"
<br> replace(str1, src, dest) = "${fn:replace(str1, " ", "-")}"
<br> indexOf(str1, str2) = "${fn:indexOf(str1, str2)}"
<br> startsWith(str1, str2) = "${fn:startsWith(str1, 'Fun')}"
<br> endsWith(str1, str2) = "${fn:endsWith(str1, "합니다.")}"
<br> contains(str1, str2) = "${fn:contains(str1, str2)}"
<br> containsIgnoreCase(str1, str2) =
"${fn:containsIgnoreCase(str1, str2)}"
<br>
<c:set var="array" value="${fn:split(tokens, ',')}" />
join(array, "-") = "${fn:join(array, "-")}"
<br> escapeXml(str1) = "${fn:escapeXml(str1)}"
<br>
</body>
</html>
'Language > JSP' 카테고리의 다른 글
09장_표현언어(Expression Language) (0) | 2023.01.26 |
---|---|
08장_ 클라이언트와의 대화2 : 세션 (1) | 2023.01.20 |
03장_JSP로 시작하는 웹 프로그래밍 (0) | 2023.01.19 |