java/study
JSP 커스텀 태그 JSTL 포매팅라이브러리
dalae6763
2023. 3. 30. 13:49
jsp 커스텀 태그 jstl
JSTL 코어(core) 라이브러리 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set>
- EL 식 변수로 추가 - scope - page : pageContext 속성(기본값) - request - session - application
<c:remove>
-> 속성값에서 제거 -> 적용 범위를 설정하지 않으면 설정된 속성명의 모든 속성의 값을 제거 - scope로 범위 설정 -> 특정 범위의 속성만 제거 가능
<c:if>
- 조건문
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="num1" value="300" /> <c:set var="num2" value="200" /> <c:if test="${num2 > num1}"> num2가 더 큽니다. </c:if> <c:if test="${num1 >= num2}"> num1이 num2보다 크거나 같다. </c:if> <br> ${num2 > num1 ? "num2가 더 큽니다." : "num1이 num2보다 크거나 같다" }
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:set var="age" value="18" /> <c:choose> <c:when test="${age < 8}"> 유치원생! </c:when> <c:when test="${age < 14}"> 초등학생! </c:when> <c:when test="${age < 17 }"> 중학생! </c:when> <c:when test="${age < 20}"> 고등학생! </c:when> <c:otherwise> 성인! </c:otherwise> </c:choose>
<c:forEach>
- 반복문
- brgin:시작번호
- end:종료번호
- step:증감단위(기본값1)
- var:begin,end→현재수치
- items: el식 변수()
- 배열
- 컬렉션(collection-list,set)
- itrator
- enumeration
- +var:반복하는 각각의 요소
- -varStatus
- 반복에 대한 상태값
- index:0부터 시작하는 반복횟수
- count:1부터 시작하는 반복횟수
- frist: 첫번째 반복인지 체크
- last:마지막 반복인 체크
- current:
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.util.*, models.Member" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="i" begin="1" end="10" step="2">
<h1>${i}</h1>
</c:forEach>
<%
List<Member> members = new ArrayList<>();
for(int i = 1; i <= 10; i++) {
members.add(new Member("userId" + i, "123456", "사용자" + i));
}
pageContext.setAttribute("members", members);
%>
<table border='1'>
<thead>
<tr>
<th>순번</th>
<th>아이디</th>
<th>비밀번호</th>
<th>회원명</th>
</tr>
</thead>
<tbody>
<c:forEach var="member" items="${members}" varStatus="status">
<%--member==status.current--%>
<%-- member == status.current --%>
<tr>
<td>${status.count}</td>
<td>${status.current.userId}</td>
<td>${member.userPw}</td>
<td>${member.userNm}</td>
</tr>
</c:forEach>
</tbody>
</table>
<%@page contentType="text/html; charset=utf-8"%>
<%@page import="java.util.*,models.Member"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach var="i"begin="1"end="10"step="2">
<c:redirect>
(태그? clite를 사용하면 편하게 사용 할 수 있다.)
- HttpServletResponse
- response
- .sendRedirect(주소)
- 응답 헤더
- Location:주소
- url: 주소
<%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:redirect url="https://www.naver.com" />
- response
<c:out…>
- 출력→html escape: html태그를 문자열로 인식
<h1>제목!</h1>
이상태 그대로 나옴
- escape 처리
- seacapeXml:기본값 true: Html태그를 escape처리(문자열 인식)
- false→html태그를 인식
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="html" value="<h1>제목!</h1>" />
<c:out value="${html}" escapeXml="false" />
<a href="<c:url value='/jstl/ex04.jsp' />">ex04 이동</a>
<c:url…>
- -컨텍스트 패스
- 환경에 따라 url주소가 알아서 바뀌는게 context path
<a href="<c:url value=e/jstl/ex04.jsp>"/>ex04이동</a>
<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <c:set var="html" value="<h1>제목!<h1>"/> <c:out value="${html}" escapeXml="false"/> <c:url var="html" value="<h1>제목!<h1>"/>
<c:import>
- <jsp:include page=”페이지”/>:버퍼추가
- 차이점
- url=”주소”
- 액션태그인 include는 현재 서버의 자원만 가능
- jsp,서블릿,html,텍스트
- import는 현재 서버 자원+외부 서버 자원
- var입력시 → 출력결과물 el변수에 담아준다
포매팅 라이브러리
형식화&국제화,지역화
fmt:formatDate
- 지금은?
- java.time.*
- java.time.format
- DateTimeFormatter
- type
- date:날짜만 표기(기본값)
- time:시간만표기
- both:날짜+시간
- dateStyle
- timeStyle
- short|medium|long|full
<%@page content="text/html; charset=utf-8"%> <%@ page import="java.util.*"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%date date = new date();%> <c:set var="date" value="<%=date%>"/> <fmt:formatdate value="${date}" type="time"/><--시간--> <br> <fmt:formatdate value="${date}" type="both" dateStyle="short"/><--날짜 시간 분--> <br> <fmt:formatdate value="${date}" type="both" dateStyle="medium"/> <br> <fmt:formatdate value="${date}" type="both" dateStyle="long"/><---> <br> <fmt:formatdate value="${date}" type="both" dateStyle="full"/><---->
- pattern:날짜 형식
<fmt:formatdate value="${date}" type="both"pattren="yyyy.MM.dd. HH:mm"/><--내가 원하는대로 잘사용하지않는다-->
- short|medium|long|full
- date:날짜만 표기(기본값)
fmt:formatNumber
- 숫자 형식화
- java.text패키지
- DecialFormat
- value
- groupingUsed:true:true→숫자 세자리 마다,(⭕)
- groupingUsed:true:False→숫자 세자리 마다,(❌)
<%@page contentType="text/htmll charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/core"%> <fmt:formatNumber value="100000000" groupingUsed="false" /><--숫자사이에 콤마-->
pattern
#
0
<%@page contentType="text/htmll charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/core"%> <fmt:formatNumber value="100000000" groupingUsed="false"/> <br> <fmt:formatNumber value"10.1234" pattern="#.###"/> <br> <fmt:formatNumber value"10.1234" pattern="0.000"/><--3번째 소수점까지--> <br> <fmt:formatNumber value"100000" pattern="#,####"/><--세자리이후로 반복-->
type
currency-통화
<%@page contentType="text/htmll charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/core"%> <fmt:formatNumber value"10000" type="currency"/>
percnet-%
<%@page contentType="text/htmll charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/core"%> <fmt:formatNumber value"0.2" type="percent"/><--20%-->
- java.text패키지
fmt:setLocale
- Locale→지역화
- java.util.Locale→국가,언어
- value
- 언어코드_국가코드(kr)
- 언어코드(ko)
<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"> <%@taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"> <fmt:setLocale"ko_kr"/> <fmt:formatNumber value"10000" type="currency"/><br>
💡10000원<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"> <%@taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"> <fmt:setLocale"en_us"/> <fmt:formatNumber value"10000" type="currency"/><br>
💡$10000
fmt:timeZone과fmt:setTimeZone
- fmt:timeZone→적용되는 날
- 태그 안에서만
<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%> <% Date date = new date(); %> <c:set var="date" value="<%date%>"/> <fmt:timeZone value="America/New_York" type="both"/> 뉴욕:<fmt:formatDate value="${date}"type="both"/> </fmt:timeZone>
- fmt:settimeZone
- set아래부터 끝까지.
<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%> <% Date date = new date(); %> <c:set var="date" value="<%date%>"/> <fmt:setTimeZone value="Asia/Sydney"/> 시드니 : <fmt:formatdate value="${date}" type="both"/>
fmt:setBundle과fmt:bundle
- <fmt:message>
- resources→mesage make folder connons.properties make file
userId=아이디 emali=이메일
<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <fmt:setBundle basename="messages.commons"/> <fmt:message key="userId">
- resources→mesage make folder connons.properties make file
- properties:설정,메세지(다국어)
- 키-값
- #→주석
- 병렬 리소스 방식
- commons_ko.properties→한국어
- commons_en.properties→영어
- java.text.패키지
- ResourceBundle
fmt:requestEncoding
- request.setCharacterEncoding(…)
<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <form method="post" action="ex14_ps.jsp"> 이름:<input type="text" name="name"> <button type="submit">전송</button> 이메일 </form>
<%@page contentType="text/html; charset=utf-8"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% request.setCharacterEncoding("UTF-8"); %> <fmt:requestEncoding value"UTF-8"/> ${param.name}
functions 라이브러리
- we
<%@page content="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"%>
${fn:toUpperCase("abc")}
💡
ABC
<%@page content="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"%>
${fn:toUpperCase("abc")}
<c:forEach var="item" items="${fn:split('apple,orange,bamama',',')}">
${item}<br>
</c:forEach>
<%@page content="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"%>
<%
String[] names = {"이름1","이름2","이름3"};
pageContext.setAttribute("names",names);
%>
${fn:toUpperCase("abc")}
<c:forEach var="item" items="${fn:split('apple,orange,bamama',',')}">
${item}<br>
</c:forEach><br>
${fn:join(names,",")}
참고
${param.name}
은 form에서 전송된 name 파라미터의 값을 나타냅니다. 이 값은 사용자가 입력한 값으로, 해당 JSP 페이지에서 이 값을 사용할 수 있습니다.
예를 들어, 사용자가 아래와 같은 form을 전송했다고 가정합니다.
<form method="post" action="example.jsp">
<label for="name">이름:</label>
<input type="text" id="name" name="name">
<input type="submit" value="전송">
</form>
이 경우, example.jsp
페이지에서 ${param.name}
을 사용하여 사용자가 입력한 이름을 출력할 수 있습니다.
<p>안녕하세요, ${param.name}님!</p>
위 예시에서 ${param.name}
은 "name"이라는 파라미터의 값을 출력합니다. 이 예시에서는 사용자가 입력한 이름을 출력합니다.
Uploaded by N2T