JSTL 기초
JSP Standard Tag Library
- JSP에서 계속 자바코드를 쓰다보면.. 로직과 뷰가 분리되지 않아 협업시 여러가지 문제가 발생함에 따라 생겨난 라이브러리
연산자 구분 | 연산자 |
---|---|
관계 | < lt > gt <= le >= ge == eq != ne |
산술 | + - * / div % mod |
논리 | && and || or ! not |
Empty | empty |
- jsp파일 상단에 다음을 추가한다
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
단 이전에 jstl-1.2.jar, standard.jar 가 lib폴더에 추가되어 있어야 함
예제
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<!-- 변수선언 -->
<c:set var="name" value="alice"/>
<c:set var="age" value="23"></c:set>
<!-- 변수출력 -->
<c:out value="${name}"></c:out><br>
<c:out value="${age }"></c:out><br>
<!-- 변수 간단하게 출력하기 -->
${name} <br> ${age} <br>
<!-- 변수 두개 추가로 선언하기 -->
<c:set var="su1" value="7"></c:set>
<c:set var="su2" value="4"></c:set>
<c:set var="msg" value="^^"></c:set>
<table border="1">
<caption>연산자 공부하기</caption>
<tr>
<th>연산자</th>
<th>결과값</th>
</tr>
<tr>
<td>\${su1+su2 }</td>
<td>${su1+su2 }</td>
</tr>
<tr>
<td>\${su1-su2 }</td>
<td>${su1su2 }</td>
</tr>
<tr>
<td>\${su1*su2 }</td>
<td>${su1*su2 }</td>
</tr>
<tr>
<td>\${su1/su2 }</td>
<td>${su1/su2 }</td>
</tr>
<tr>
<td>\${su1%su2 }</td>
<td>${su1%su2 }</td>
</tr>
<tr>
<td>\${su1 div su2 }</td>
<td>${su1 div su2 }</td>
</tr>
<tr>
<td>\${su1 mod su2 }</td>
<td>${su1 mod su2 }</td>
</tr>
<tr>
<td>\${empty msg }</td>
<td>${empty msg }</td><!-- 비어있냐고 물어봄 -->
</tr>
<tr>
<td>\${su1 > su2 }</td>
<td>${su1 > su2 }</td>
</tr>
<tr>
<td>\${su1 gt su2 }</td>
<td>${su1 gt su2 }</td>
</tr>
<tr>
<td>\${su1 == su2 }</td>
<td>${su1 == su2 }</td>
</tr>
<tr>
<td>\${su1 eq su2 }</td>
<td>${su1 eq su2 }</td>
</tr>
<tr>
<td>\${su1 != su2 }</td>
<td>${su1 != su2 }</td>
</tr>
<tr>
<td>\${su1 ne su2 }</td>
<td>${su1 ne su2 }</td>
</tr>
<tr>
<td>\${su1>su2 && su1>50 }</td>
<td>${su1>su2 && su1>50 }</td>
</tr>
<tr>
<td>\${su1>su2 and su1>50 }</td>
<td>${su1>su2 and su1>50 }</td>
</tr>
<tr>
<td>1증가시키기. 증감연산자없음</td>
<td>
<c:set var="su1" value="${su1+1 }"></c:set>
${su1 }
</td>
</tr>
</table>
</body>
</html>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<fmt:requestEncoding value="UTF-8"/>
<form action="Ex2_param.jsp" method="post">
이름입력 : <input type="text" name="name" size="10"><br>
나이입력 : <input type="text" name="age" size="5"><br>
<input type="submit" value="submit">
</form>
<hr>
<c:if test="${!empty param.name}"> <!-- not empty라고 적어도 된다. -->
<h2>결과출력</h2>
이름 : ${param.name }<br>
나이 : ${param.age }
</c:if>
</body>
</html>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<fmt:requestEncoding value="UTF-8"/>
<form action="Ex3_dto_param.jsp" method="post">
이름입력 : <input type="text" name="name" size="10"><br>
나이입력 : <input type="text" name="age" size="5"><br>
주소입력 : <input type="text" name="addr" size="10"><br>
<input type="submit" value="submit">
</form>
<hr>
<c:if test="${not empty param.name }">
<jsp:useBean id="dto" class="test.code.DataDTO"></jsp:useBean>
<jsp:setProperty property="*" name="dto"/>
<pre>
이름 : ${dto.name }
나이 : ${dto.age }
주소 : ${dto.addr}
</pre>
</c:if>
</body>
</html>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<c:set var="msg" value="happy"> </c:set>
msg : ${msg}<br>
<%
String name="alice";
%>
name : ${name }<br> <!-- 그냥 자바에서 저장된 변수는 안나옴 -->
<%
String addr = "seoul";
request.setAttribute("addr", "requested address");
session.setAttribute("blood", "session blood");
%>
address : ${addr }<br> <!-- request에서 자동으로 addr을 찾는다. -->
address : ${requestScope.addr }<br> <!-- 위랑 같은 의미 -->
blood : ${sessionScope.blood }<br> <!-- 세션에서도 가져올 수 있다. -->
<%
String name1 = "bob";
%>
<c:set var="name1" value="<%=name1 %>"/>
name1 : ${name1 }
</body>
</html>
<%@page import="java.util.List"%>
<%@page import="java.util.Vector"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<%
List<String> list = new Vector<String>();
list.add("rose");
list.add("daisy");
list.add("tulip");
list.add("sunflower");
list.add("sakura");
request.setAttribute("list1",list);
%>
<!-- 자바영역에서 벡터선언후 리퀘스트에 저장한 변수 출력하기 -->
<c:forEach var="a" items="${list1 }">
${a}<br>
</c:forEach>
<hr>
<!-- 자바영역의 벡터 변수를 JSTL의 변수로 반환 후 출력하기 -->
<c:set var="list2" value="<%=list %>"/>
<c:forEach var="b" items="${list2 }">
${b}<br>
</c:forEach>
</body>
</html>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<h2>JSTL에서의 forEach문 공부하기</h2>
<hr>
<h4>1~10 출력하기</h4>
<c:forEach var="n" begin="1" end="10" step="1"><!-- step은 1일경우 생략가능 -->
${n } 
</c:forEach>
<br>
<c:forEach var="n" begin="1" end="100" step="5">
${n } 
</c:forEach>
<%
List<String> list = new ArrayList<String>();
list.add("red");
list.add("blue");
list.add("orange");
list.add("pink");
list.add("yellow");
list.add("grey");
request.setAttribute("list1",list);
%>
<hr>
<!-- 리스트컬렉션 출력하기 - 전체 다 -->
<c:forEach var="s" items="${list1 }" varStatus="a">
${a.count }/${a.index } : <b style="color:${s};">${s }</b><br>
<!-- count는 단순 일련번호, index는 실제 배열의인덱스를 의미 -->
</c:forEach>
<br>
<hr>
<!-- 리스트컬렉션 출력하기 - 부분 -->
<c:forEach var="s" begin="2" end="5" items="${list1 }" varStatus="a">
${a.count }/${a.index } : <b style="color:${s};">${s }</b><br>
</c:forEach>
</body>
</html>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<%
String str[] ={"pink", "orange", "green", "skyblue", "grey", "black", "magenta", "blue"};
%>
<c:set var="str" value="<%=str %>"></c:set>
<table border="1">
<tr>
<c:forEach var="n" items="${str }" varStatus="i">
<th width="100px" style="color:${n}">${(i.index+2) }단</th>
</c:forEach>
</tr>
<c:forEach var="a" begin="1" end="9">
<tr>
<c:forEach var="b" items="${str }" varStatus="i">
<td>
<c:set var="dan" value="${i.count+1 }"></c:set>
<b style="color:${b}">${a }x${dan }=${a*dan }</b>
</td>
</c:forEach>
</tr>
</c:forEach>
</table>
</body>
</html>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<h2>문자열을 컴마로 구분하여 출력해보자!</h2>
<c:set var="str" value="red,blue,green,grey,orange"></c:set>
<c:forTokens items="${str }" delims="," var="n" varStatus="i"> <!-- delims : 구분자 -->
${i.count } : ${n } <br>
</c:forTokens>
</body>
</html>
c:choose, c:when, c:otherwise
- < c:choose/> 태그는java 의switch 문과 같지만, 조건에 문자열 비교도 가능하고 쓰임의 범위가 넓다. 또한 < c:if/ > 태그에else가 없기 때문에 이의 대체 기능도 수행한다.
<c:choose>
body content
(하나 이상의 <when> 과 하나 이하의 <otherwise> 서브태그)
<c:when test="조건">
body content
</c:when>
<c:otherwise>
conditional block
</c:otherwise>
</c:choose>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<fmt:requestEncoding value="UTF-8"/>
<form action="Ex9_choose.jsp">
<h5>가고 싶은 나라를 선택하세요</h5>
<b>나라: </b>
<select name="nara">
<option value="-">select country</option>
<option value="usa">usa</option>
<option value="china">china</option>
<option value="japan">japan</option>
<option value="korea">korea</option>
</select>
<input type="submit" value="submit">
</form>
<hr>
<c:set var="nara" value="${param.nara }"></c:set>
<c:if test="${nara != '-' }">
<c:choose>
<c:when test="${nara == 'usa' }">
<b> USA is broad</b>
</c:when>
<c:when test="${nara == 'china' }">
<b> China is red</b>
</c:when>
<c:when test="${nara == 'japan' }">
<b> japan has sushi</b>
</c:when>
<c:when test="${nara == 'korea' }">
<b> korea is my country</b>
</c:when>
</c:choose>
</c:if>
</body>
</html>
fmt : formatNumber
- 숫자 형식을 표현하는 태그
Syntax 1: body 없는 경우
<fmt:formatNumber value="numericValue"
[type="{number|currency|percent}"]
[pattern="customPattern"]
[currencyCode="currencyCode"]
[currencySymbol="currencySymbol"]
[groupingUsed="{true|false}"]
[maxIntegerDigits="maxIntegerDigits"]
[minIntegerDigits="minIntegerDigits"]
[maxFractionDigits="maxFractionDigits"]
[minFractionDigits="minFractionDigits"]
[var="varName"]
[scope="{page|request|session|application}"]/>
Syntax 2: 형식에 맞출 수치가 body에 있는 경우
<fmt:formatNumber [type="{number|currency|percent}"]
[pattern="customPattern"]
[currencyCode="currencyCode"]
[currencySymbol="currencySymbol"]
[groupingUsed="{true|false}"]
[maxIntegerDigits="maxIntegerDigits"]
[minIntegerDigits="minIntegerDigits"]
[maxFractionDigits="maxFractionDigits"]
[minFractionDigits="minFractionDigits"]
[var="varName"]
[scope="{page|request|session|application}"]>
형식화될 수치
</fmt:formatNumber>
fmt : formatDate
- 날짜 형식을 표현하는 태그
<fmt:formatDate value="date"
[type="{time|date|both}"]
[dateStyle="{default|short|medium|long|full}"]
[timeStyle="{default|short|medium|long|full}"]
[pattern="customPattern"]
[timeZone="timeZone"]
[var="varName"]
[scope="{page|request|session|application}"]/>
<%@page import="java.util.Date"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<c:set var="num1" value="789564"></c:set>
<c:set var="num2" value="34.67898"></c:set>
<h3>숫자 포맷 양식</h3>
<fmt:formatNumber type="currency" value="${num1 }"></fmt:formatNumber><br>
<fmt:formatNumber type="number" value="${num1 }"></fmt:formatNumber><br>
<fmt:formatNumber value="${num1 }" pattern="#,##0"></fmt:formatNumber> <br><!--패턴으로 줘도 된다. -->
<fmt:formatNumber type="percent" value="${num2 }"></fmt:formatNumber><br>
<fmt:formatNumber value="${num2 }" pattern="0.0"></fmt:formatNumber><br>
<!-- 소수점 이하 절삭하기 -->
<fmt:parseNumber value="${num2 }" integerOnly="true"></fmt:parseNumber>
<h3>날짜포맷양식</h3>
<c:set var="day" value="<%=new Date() %>"></c:set>
그냥 출력하기: ${day }<br>
<fmt:formatDate value="${day }" type="date"/><br>
<fmt:formatDate value="${day }" type="time"/><br>
<fmt:formatDate value="${day }" type="both"/><br>
<fmt:formatDate value="${day }" pattern="yyyy-MM-dd HH:mm"/><br>
<fmt:formatDate value="${day }" pattern="yyyy-MM-dd a hh:mm"/><br>
<fmt:formatDate value="${day }" pattern="yyyy-MM-dd a hh:mm EEE"/><br>
<fmt:formatDate value="${day }" pattern="yyyy-MM-dd a hh:mm EEEE"/><br>
<fmt:formatDate value="${day }" pattern="yyyy년 MM월 dd일 a hh시 mm분 EEEE"/><br>
</body>
</html>
<%@ 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" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<h3>JSTL 함수 공부 </h3>
<!-- 특정 문자열에 단어가 포함되어 있는지 체크 : 결과는 boolean -->
${fn:contains("Have a nice day","nice")}<br>
<c:set var="msg" value="happy,hello,nice,good"></c:set>
<c:if test="${fn:contains(msg,'happy')==true}">나는 행복합니다...</c:if>
<c:if test="${fn:contains(msg,'happy')==false}">나는 행복합니다...</c:if>
<hr>
<!-- 특정 단어로 끝나는지, 시작하는지 확인 -->
${fn:startsWith("happynice","hap") }<br>
${fn:endsWith("happynice","ice") }<br>
<hr>
<!-- 특정문자열의 길이 구하기 -->
${msg}의 길이: ${fn:length(msg) }<br>
<hr>
<!-- 단어 사이사이에 문자 삽입하기 : 문자열 -> 배열 -> 다시 문자열 -->
<c:set var="texts" value="${fn:split('hi my name is lee',' ') }"></c:set>
<c:forEach var="s" items="${texts }">
${s }<br>
</c:forEach>
<c:out value="${fn:join(texts,'-') }"></c:out>
<hr>
<!-- 문자 대치 replace -->
${fn:replace(msg,'o','*')}<br>
<hr>
<!-- 문자열 추출 -->
<c:set var="myname" value="Lee Young Ja"></c:set>
${fn:substring(myname,4,7) }<br><!-- 4번 인덱스부터 6번 인덱스까지 추출 -->
<hr>
<!-- 대소문자 변환하여 출력 -->
${fn:toLowerCase(myname) }<br>
${fn:toUpperCase(myname) }<br>
<hr>
<!-- 공백제거하기 -->
<c:set var="str1" value=" hahahaha "></c:set>
공백제거 전 문자열 길이 : ${fn:length(str1) }
<c:set var="str2" value="${fn:trim(str1) }"></c:set><br>
공백제거 후 문자열 길이 : ${fn:length(str2) }
</body>
</html>
실습문제
자바영역에 벡터선언후 이름 10개 저장,
input 에 성을 입력하면 그 성씨에 해당하는 사람 출력하기
<%@page import="java.util.Vector"%>
<%@page import="java.util.List"%>
<%@ 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" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<fmt:requestEncoding value="UTF-8"/>
<%
List<String> list = new Vector<String>();
String str[] = {"이영자","김복순","장순복","하영실","이금자","박복례","이서현","박장금","김상현","장중현"};
for(int i = 0 ; i < str.length ; i++){
list.add(str[i]);
}
%>
<form action="Ex12_test.jsp" method="post">
성 입력: <input type="text" size="10" name="firstName"> <input type="submit" value="submit">
</form>
<c:if test="${not empty param.firstName }">
<hr>
<c:set var="firstname" value="${param.firstName }"></c:set>
<c:forEach var="n" items="<%=list %>" varStatus="i">
<c:if test="${fn:startsWith(n,firstname)==true}">
${n }<br>
</c:if>
</c:forEach>
</c:if>
</body>
</html>
이제 지옥같은 < % % > 에서 벗어나자!
Comments