상세 컨텐츠

본문 제목

JSTL

Java

by 탑~! 2014. 12. 10. 16:41

본문

http://jstl.java.net/ 에서 아래 두개 다운로드.

JSTL API

JSTL Implementation


이클립스에서 WEB-INF/lib/로 드래그하여 삽입


JSTL

JSTL


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>



기능 분류

태그

설명

변수 및 값의지정

set

JSP에서 사용될 변수 및 값을 지정한다.

remove

지정한 변수를 삭제한다.

조건 및 흐름제어

if

조건에 따라 내부 코드를 수행한다.

choose

다중 조건을 처리할 때 사용된다.(Java 문법의 switch 구문과 비슷)

forEach

콜렉션이나 Map의 각 항목을 처리할 때 사용된다.

forTokens

구분자로 분리된 각각의 토큰을 처리할 때 사용된다.

포함과리다이렉션태그

import

다른 JSP 페이지등의 자원 수행 결과를 삽입한다.

redirect

지정한 경로로 리다이렉트한다.

url

URL을 지정한다.

출력 태그

out

내용을 알맞게 처리한 후 출력한다.

예외 처리 태그

catch

예외 처리에 사용된다



 



set  & remove

set & remove


<c:set var="variable name" scope="request" value="some value" />


var - 변수의 이름

scope - 변수를 저장할 영역을 지정한다. 영역을 지정하는 값으로는 page, request, session, application중의 하나가 된다.

value - 변수의 값을 지정한다. 표현식이나 EL을 사용하여 값을 지정할 수 있다.



<c:set var="variable name" scope="request">

some value

</c:set>


<c:remove var="variable name" scope="request" />





<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

int n1 = 100// 스크립트릿에서 선언된 변수 n1은 JSTL 및 EL에서 활용할 수 없다.

%>


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

<c:set var="n2" value="${100}"/>

<c:set var="n3" scope="request">100.5</c:set>


<html>

<head><title>set 태그와 remove 태그</title></head>

<body>


스크립트릿 선언 변수를 표현식으로 출력하기 n1=<%= n1 %><br/>

스크립트릿 선언 변수를 EL로 출력하기 n1 = ${n1} <br/>

<hr/>

변수 n2 = ${n2} <br/>

변수 n3 = ${n3} <br/>

n2 + n3 = ${n2 + n3} <br/>

현재의 시각은 ${now} 입니다.

<hr/>

<c:remove var="n1" scope="page" />

<c:remove var="n2" scope="page" />

<c:remove var="n3" scope="page" />


Remove 이후의 n2 = ${n2} <br/>

Remove 이후의 n3 = ${n3} <br/> <!-- scope가 request여서 삭제되않음 -->

Remove 이후의 n2 + n3= ${n2 + n3}<br/>

<hr/>

스크립트릿 선언 변수 n1=<%= n1 %>


</body>

</html>




scope객체에 변수저장


<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>session범위로 변수 저장</title></head>

<body>

<c:set var="answer" value="${1 + 2 * 4 - 6 / 2}" scope="session" />

Click <a href="viewSession.jsp">here</a> to view answer

</body>

</html>


scope객체에서 변수참조


<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>session범위의 변수 값 읽기</title></head>

<body>

The answer is <c:out value="${sessionScope.answer}" /> <br/>

The answer is <c:out value="${answer}" /> <br/>

</body>

</html>




set 태그를 사용하면 target 속성과 property 속성을 통해서 자바빈 프로퍼티의 값이나 Map의 키 값을 지정할 수 있다.


<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<c:set var="map" value="<%= new java.util.hashmap() %>" />

<c:set var="member" value="<%= new thinkonweb.bean.member() %>" />


<html>

<head><title>set 태그와 map 객체 활용</title></head>

<body>

<c:set target="${map}" property="id" value="20091010" />

<c:set target="${member}" property="name" value="홍길동" />

map 객체에 저장된 id 값: ${map.id}<br/>

member 객체에 저장된 name 값: ${member.name}

</body>

</html>




forEach태그와 함께 작성

<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="char" value="A,B,C" />

<html>

<head><title>set 태그 2</title></head>

<body>

<c:forEach var="i" items="${char}">

${i<br/>

</c:forEach>

</body>

</html>



if

if


test 속성 값에는 true나 false를 리턴하는 조건식이 오는데 주로 EL을 활용한 조건식이 온다. 이 조건식의 결과값이 true이면 if블록이 처리된다


<c:if test="조건식“>

...

...

</c:if>



<c:if test="조건“ var="변수 이름">

...

...

</c:if>

or

<c:if test="조건“ var="변수 이름" />





<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>if 태그</title></head>

<body>

<c:if test="true">

숫자 맞히기 게임 (무조건 출력) <br/><br/>

</c:if>


<form method="post">지금 제가 무슨 숫자를 생각하고 있을까요?

<input type="text" name="guess" />

<input type="submit" value="Try!" />

</form>


<c:if test="${empty sessionScope.numTry}">

<c:set var="numTry" value="1" scope="session" />

</c:if>


시도 횟수: ${sessionScope.numTry} <br/>


<c:if test="${pageContext.request.method=='POST'}">

<c:if test="${param.guess=='5'}">

빙고! 숫자를 맞혔네요!

<c:set var="numTry" value="${1}" scope="session" /> <br/><br/>

</c:if>


<c:if test="${param.guess!='5'}">계속 맞혀 보세요~~~

<c:set var="numTry" value="${sessionScope.numTry + 1}" scope="session" /> <br/><br/>

</c:if>

</c:if>


</body>

</html>




조건식의 수행 결과만을 얻어 오기 위해서는 if 태그의 몸체가 필요 없기 때문에 시작과 동시에 끝나는 if 태그를 사용할 수 있다


<c:if test="${pageContext.request.method=='POST'}">

<c:if test="${param.guess=='5'}" var="result"/>

결과는 ${result} /* true or false로만 출력됨 */

</c:if>


 


 

choose

choose


<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>choose 태그 예제</title></head>

<body>

당신은 다음의 수를 입력했습니다:

<c:choose>

<c:when test="${param.enter=='1'}">One<br/></c:when>

<c:when test="${param.enter=='2'}">Two<br/></c:when>

<c:when test="${param.enter=='3'}">Three<br/></c:when>

<c:when test="${param.enter=='4'}">Four<br/></c:when>

<c:when test="${param.enter=='5'}">Five<br/></c:when>

<c:otherwise> <c:out value="${param.enter}" /><br/> </c:otherwise>

</c:choose>

<form method="get">1부터 5사이의 수를 입력하세요:

<input type="text" name="enter"/>

<input type="submit" value="Accept"/>

</form>

</body>

</html>




forEach

forEach


<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%

java.util.hashmap mapData = new java.util.hashmap();

mapData.put("name""jspbook");

mapData.put("today"new java.util.Date());

%>

<c:set var="intArray" value="<%= new 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"> /* 자바의 for명령처럼활용 */

<c:set var="sum" value="${sum + i}" />

</c:forEach>

결과 = ${sum}



<h4>구구단: 4단</h4>

<ul>

<c:forEach var="i" begin="1" end="9"> /* 자바의 for명령처럼활용 */

<li>4 * ${i= ${4 * i}

</c:forEach>

</ul>



<h4>int형 배열</h4>

<c:forEachvar="i" items="${intArray}" begin="2" end="4"> /* 배열의 특정위치만 추출 */

[${i}]

</c:forEach>



<h4>map</h4>

<c:forEachvar="i" items="${map}"> /* 객체배열도 사용가능 */

${i.key= ${i.value}<br>

</c:forEach>


</body>

</html>




/* 객체배열도 사용가능 */


<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<c:set var="ids" value="<%= java.util.TimeZone.getAvailableIDs() %>" />

<c:forEachvar="i" items="${ids}">

${i}<br/>

</c:forEach>

</html>

 



forTokens

forTokens

forTokens 태그는 java.util.StringTokenizer 클래스와 같은 기능을 제공하는 태그


<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>forTokens 태그</title></head>

<body>


콤마와 점을 구분자로 사용:<br>

<c:forTokens var="token" items="빨강색,주황색.노란색.초록색,파랑색,남색.보라색" delims=",.">

${token}

</c:forTokens>


</body>

</html>




import

import


import 태그는 <jsp:include> 태그와 비슷한 기능을 제공하는 태그


<c:import url="http://www.daum.net/" charEncoding="euc-kr" var="daumnews" scope="request">

<c:param name="_top_G" value="news"/>

</c:import>


url - 읽어 올 URL

charEncoding - 읽어 올 데이터의 캐릭터 셋

var - 읽어 온 데이터를 지정할 변수명

scope - 변수를 저장할 범위 지정

param - <jsp:param> 태그처럼 전송할 파라미터의 이름과 값을 지정할 때 사용


<jsp:include> 태그와 <c:import> 태그의 차이점이 있다면 <c:import> 태그는 같은 웹 어플리케이션

디렉터리에 포함되지 않았더라도 그리고 심지어 같은 서버에 있지 않은 지원에 대해서도 접근할 수 있다.


import 태그를 사용할 때 한 가지 주의해야 할 점은 import 태그를 사용한다고 해서 읽어 온

내용이 곧바로 import 태그 위치에 포함되지 않는다는 점이다. url 속성에 명시한 서버에 접

속해서 읽어 온 데이터는 var 속성에 명시한 변수에 저장되기 때문이다. 읽어 온 결과 화면이

변수에 저장되기 때문에 읽어 온 데이터를 쉽게 원하는 형태로 변경할 수 있게 된다.




<% @ page contentType = "text/htm l; charset=euc-kr" % >

헤더 내용 header.jsp



<% @ page contentType = "text/htm l; charset=euc-kr" % >

몸체 내용: ${param .id} body.jsp




<% @ page contentType = "text/htm l; charset=euc-kr" % >

꼬리글 내용 footer.jsp





<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:import url="header.jsp" var="head" />

<c:import url="body.jsp" var="body">

<c:param name="id" value="jspbook" />

</c:import>

<c:import url="footer.jsp" var="foot" />


<html>

<head><title>import와 url 태그</title></head>

<body>

${head}<br/><br/>

${body}<br/><br/>

${foot}

</body>

</html>






redirect

redirect


redirect 태그는 지정한 페이지로 리다이렉트할 때 사용된다. response.sendRedirect()와 비슷한 기능을 제공한다


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:redirect url="ifTag.jsp">

<c:param name="name" value="bk"/>

</c:redirect>



url

url

url 태그는 URL을 생성해서 변수에 저장할 때 사용



urlform.jsp

<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>url 폼</title></head>

<body>

<form action="createU RL.jsp" method="post">

<table>

<tr>

<td>이름:</td>

<td><input type="text" name="name" /></td>

</tr>

<tr>

<td>나이:</td>

<td><input type="text" name="age" /></td>

</tr>

</table>

<input type="submit" value="완료" />

</form>

</body>

</html>





createURL.jsp

<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<% request.setCharacterEncoding("euc-kr"); %>


<c:url value="displayValues.jsp" var="displayURL">

<c:param name="name" value="${param.name}" />

<c:param name="age" value="${param.age}" />

</c:url>


<html>

<head><title>url 생성</title></head>

<body>

생성된 URL<c:out value="${displayURL}" /> <br /> /* displayValues.jsp?name=woosic&age=20 형태로 만들어 */

Click <a href='<c:out value="${displayURL}" />'>here</a> to go the url.

</body>

</html>





displayValues.jsp

<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>파라미터 값 보기</title></head>

<body>

<c:forEach var="currentParam" items="${param}">

<c:out value="${currentParam.key}" />=

<c:out value="${currentParam.value}" /><br />

</c:forEach>

</body>

</html>




 

out

out

<c:out value="value" escapeXml="{true|false}" default="defaultValue"/>


value - 브라우저로 출력할 값을 나타낸다. 일반적으로 value 속성의 값은 String과 같은 문자열이다.

escapeXml - 이 속성의 값이 true일 경우 아래 같이 문자를 변경한다. 생략할 수 있으며, 생략할 경우 기본값은 true이다.

< <

> >

& &

' '

" "




<%@ page contentType = "text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="a" value="<B>ABC</B>" />

${a}<BR>

<c:out value="${a}"/><BR>

<c:out value="${a}" escapeXml="true"/><BR>

<c:out value="${a}" escapeXml="false"/><BR>

<c:out value="${b}" escapeXml="false" default="DEF" />



 

catch

catch


<c:catch var="exName">

...

예외가 발생할 수 있는 코드

...

</c:catch>

...

${exName} 사용


catch 태그 블록에서 예외가 발생할 경우 그 예외 객체는 exName 변수에 할당된다. 따라서

catch 태그 블록 밖에서는 exName 변수를 사용하여 예외에 따른 처리를 하면된다.



<%@ page contentType="text/html; charset=euc-kr" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title>catch태그</title></head>

<body>

<c:catchvar="ex">

name 파라미터의 값 = <%= request.getParameter("name"%><br>

<% if (request.getParameter("name").equals("test")) { %>

${param.name}은 test 입니다.

<% } %>

</c:catch>

<p>

<c:if test="${ex != null}">

예외가 발생하였습니다:<br>

${ex}

</c:if>

</body>

</html>

'Java' 카테고리의 다른 글

Java Excel 파일 생성  (0) 2014.12.19
Expression Language  (0) 2014.12.10
특정 url 소스 가져오기  (0) 2014.09.02
java document를 chm 파일로 다운로드  (0) 2014.06.10
java에서 sftp 연결하기  (0) 2014.06.10

관련글 더보기