JSTL (종류, 사용법, core, fuctions)

2021. 3. 22. 03:04 Java 관련/JSTL, EL

1. JSTL 이란?

JSTL은 JSP 표준라이브러리(JSP Standard Tag Library)의 약어이다. 자주 사용될 수 있는 커스텀 태그들을 모아서 표준으로 모아놓은 태그 라이브러리다.

JSTL 의 종류

라이브러리명 접두어 주요 기능 URI
코어 c 변수 지원, 제어문, 페이지 관련 처리 http://java.sun.com/jsp/jstl/core
함수 fn collection 처리, String 처리 http://java.sun.com/jsp/jstl/fuctions
포매팅 fmt 포맷 처리, 국제화 지원 http://java.sun.com/jsp/jstl/fmt
데이터베이스 sql DB관련 CRUD 처리 http://java.sun.com/jsp/jstl/sql
XML x XML관련 처리 http://java.sun.com/jsp/jstl/xml

사용법

위의 표에서 참고하여 JSP 상단에 <%@ taglib prefix="접두어" uri="URI 경로" %> 를 적어주면 된다. 접두어야 마음대로 쓸 수 있는 모양이지만 기왕이면 표준을 지키는게 좋지..

2. core 의 주요 기능

  • <c:set> : 변수 선언, 할당
    • scope 속성 : 범위 4가지(page, request, session, application), default 는 page
    • ex. int count = 10; = <c:set var="count" value="10">
  • <c:out> : 출력
    • ex. System.out.println("hello");을 간단하게 <c:out value="hello">
  • <c:remove> : 변수값 remove
    • scope 속성
  • <c:if> : if문, else문 없음
    • var 속성 : 조건식의 값을 저장할 변수
    • scope 속성 : boolean 변수가 사용될 범위를 뜻함
    • ex. <c:if test="조건식"> 참일때 실행할 문장 </c:if>
  • <c:choose>, <c:when>, <c:otherwise> : if-else 문 처럼 사용 가능
    • when 이 true 이면 해당 블럭 실행
    • 모든 when 이 false 이면 otherwise 블럭 실행
  <c:choose>
      <c:when test="${empty boardList}">
          등록된 글이 없습니다.
      </c:when>
      <c:when test="조건식">
          ...
      </c:when>
      <c:otherwise>
          ...
      </c:otherwise>
  </c:choose>
  • <c:forEach> : for문
    속성 설명 비고
    var 사용할 변수명 Required
    items Collection 객체(List, ArrayList) Required
    begin 시작 index(default = 0)  
    end 종료 index(default = items크기-1)  
    step 증감 수  
    varStatus 반복상태를 알 수 있는 변수  
  <c:forEach var="item" items="${list}" begin=0 end=5 step=1 varStatus="status">
      번호 : ${status.count}
      이름 : ${item.name}
      나이 : ${item.age}
      주소 : ${item.addr}
  </c:forEach>

 

3. fuctions 의 주요 기능

  • boolean startsWith(java.lang.String, java.lang.String) : 문자열A가 문자열B로 시작하는 경우, true 반환
    • ex. <a class="<c:if test="${fn:startsWith(servletPath, '/board')}">active</c:if>" href="/board">



출처: https://sjh836.tistory.com/136?category=680970 [빨간색코딩]