너와 나의 연결고리, JSP 🔗(12) - EL문, JSTL

joyfulwave·2022년 12월 1일
0
post-thumbnail




📚 EL

📌 EL문

  • Expression Language
  • 값을 간결하고 간편하게 출력할 수 있도록 해주는 언어로 <%= %>, out.println() 과 같은 자바코드를 더이상 사용하지 않고 좀 더 간편하게 출력을 지원하기 위한 도구에요.
  • 배열, 컬렉션, javabean 프로퍼티에서도 사용돼요.

⚫ 저장 범위

  • page > request > session > application

⚫ 내장 객체

  • pageContext, pageScope, requestScope,
    sessionScope, applicationScope, param, paramValues

📌 EL 표현식

  • EL구문은 ${..}내에 표현식으로 표현해요.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String data = "hello";
		// pageContext : 현재 페이지
		
		pageContext.setAttribute("data", data);
		pageContext.setAttribute("result", "pageResult");
	%>
	
	${data}<br>
	${10 + 20}<br>
	${10 > 3}<br>
	
	<%=request.getAttribute("result") %> 입니다.<br>
	${result} 입니다.<br>
	${requestScope.result} 입니다.<br>
	
	
	${names[0]}<br>
	${names[1]}<br>
	
	${notice.id}<br>
	${notice.title}<br>
</body>
</html>

📌 연산자

⚫ 기본연산자

.  => 자바빈 또는 맵에 접근하기 위한 연산자
[] => 배열 또는 리스트에 접근하기 위한 연산자
() => 우선 순위

⚫ 산술연산자

+, -, *, /(div), %(mod)

⚫ 비교연산자

==(eq), !=(ne), <(lt), >(gt), <=(le), >=(ge)

⚫ 논리연산자

&&(and), ||(or), !(not)

⚫ 조건(삼항)연산자

a? b : c => a 조건이 만족하면 b를 리턴, 아니면 c를 리턴

⚫ empty 연산자

객체의 값이 null 이거나 비어있는지를 판단, null일 경우 true 리턴
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("hello");
		arrList.add("JSP");
		arrList.add("EL");
		
		pageContext.setAttribute("list", arrList);
	%>
	
	아이디 : ${param.id}<br>
	비밀번호 : ${param.pw}<br>
	
	${list}<br>
	
	${param.id >= 3 }<br>
	${param.id ge 3 }<br>
	
	<hr><br>
	
	${empty param.id}<br>
	${!empty param.pw}<br>
	
	<hr><br>
	
	${empty param.id? '값이 비어있습니다.' : param.id }
	
</body>
</html>



📚 JSTL

📌 JSTL이란

  • JSP Standard Tag Library
  • JSTL은 연산이나 조건문, 반복문을 편하게 처리할 수 있으며, JSP 페이지 내에서 자바코드를 사용하지 않고도 로직을 구현할 수 있도록 효율적인 방법 제시해요.

📌 JSTL 선언

JSTL은 JSP파일 상단에 선언해줘요.
c와 fn은 JSTL 선언시에 prefix로 설정할 수 있어요.


📌 JSTL 태그

⚫ <c:set />

  • 변수를 만들 때 사용
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>JSTL TEST(변수)</h2>
	<!-- 
		변수선언, scope : 어느 범위까지 사용하는지, page: pageContext
		jstl로 만들어진 값은 setAttribute로 값을 넣기 때문에
		el로 값을 가져올 수 있다.
	 -->
	<c:set var="userid" value="student" scope="page"/>
	회원 아이디 : <c:out value="${userid }"/><br>
	회원 아이디 : ${userid}<br>
	
</body>
</html>

⚫ <c:out></c.out>

  • 값을 출력(EL문을 더 많이 써요.)

⚫ <c:if></c:if>

  • 조건 제어(if문)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>JSTL 제어-조건식</h2>
	<c:set var="num" value="100"/>
	<c:if test="${num gt 50 }">
		<script>
			alert("이 수는 50보다 크다");
		</script>	
	</c:if>
	<c:if test="${num gt 30 }">
		<script>
			alert("이 수는 30보다 크다");
		</script>	
	</c:if>
</body>
</html>

⚫ <c:choose></c:choose>

  • 조건 제어(switch문)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>JSTL 제어-조건식</h2>
    
	choose문 사용 <br>
	(if~else 문의 경우 jstl에서는 choose를 이용하여 구성한다.)<br>
	
	<c:choose>
		<c:when test="${num gt 50}">
			이 수는 50보다 크다!!
		</c:when>
		<c:when test="${num gt 30}">
			이 수는 30보다 크다!!
		</c:when>
		<c:when test="${num gt 10}">
			이 수는 10보다 크다!!
		</c:when>
		<c:otherwise>
			이 수는 그 외의 숫자입니다!
		</c:otherwise>
	</c:choose>
</body>
</html>

⚫ <c:when></c:when>

  • 조건 제어(case문)

⚫ <c:otherwise></c:otherwise>

  • 조건 제어
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:choose>
		<%-- param.userid가 empty일 때 --%>
		<c:when test="${empty param.userid}">
			<form>
				아이디 <input type="text" name="userid"/> <br>
				비밀번호 <input type="text" name="userpw"/> <br>
				<input type="submit" />
			</form>
		</c:when>
		<c:otherwise>
			<%-- param.userid가 empty가 아닐 때 --%>
			<c:set var = "userid" value="${param.userid }"/>
			<c:set var = "userpw" value="${param.userpw }"/>
			<c:choose>
				<c:when test="${param.userid eq 'admin'}">admin</c:when>
				<c:when test="${param.userid == 'java'}">자바학생</c:when>
				<c:otherwise>비회원</c:otherwise>				
			</c:choose>			
		</c:otherwise>
	</c:choose>
	
	<!-- 
		요청 : http://localhost:8081/jstl/jstl_test4.jsp?userid=&userpw=
			조건 1. userid값이 없을 때 => 아이디/비밀번호 입력 화면
			조건 2. userid값이 있을 때 
				조건 2-1. userid값이 admin 이면, '관리자' 출력
				조건 2-2. userid값이 java 이면, '자바학생' 출력
				조건 2-3. userid값이 그 외 값이면, '비회원' 출력
	 -->
	
</body>
</html>

⚫ <c:forEach></c:forEach>

  • 반복 제어(for문)
<%@page import="java.util.HashMap"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:forEach begin="1" end="5">
		야호<br>
	</c:forEach>
	<hr>
	<c:forEach var="cnt" begin="1" end="5">
		${cnt}<br>
	</c:forEach>
	<hr>
	<c:forEach var="i" begin="1" end="10" step="1">
		${i}<br>
	</c:forEach>
	<hr>
	<c:set var="arData" value="<%=new int[]{10, 20, 30, 40, 50} %>"/>
	<c:forEach var="a" begin="0" end="4" step="1">
		${arData[a] }
	</c:forEach>
	<hr>
	<c:forEach var="data" items="${arData }">
		${data }
	</c:forEach>
	<hr>
	<%
		HashMap<String, Integer> map = new HashMap<>();
		map.put("하나", 1);
		map.put("둘", 2);
		map.put("셋", 3);
	%>
	<c:set var="map" value="<%=map %>"/>
	<c:forEach var="entry" items="${map}">
		${entry.key } : ${entry.value }
	</c:forEach>
	<hr>
	<c:forEach var = "i" begin="1" end="9" step="1">
		5 * ${i } = ${5 * i }<br>
	</c:forEach>
</body>
</html>

📌 JSTL fn

⚫ ${fn:...} 와 같은 형태로 자바 함수를 사용할 수 있어요.

<%@page import="java.util.HashMap"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		HashMap map = new HashMap();
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");
		map.put("4", "4");
		map.put("5", "5");		
	%>
	
	<c:set var="map" value="<%=map %>"/>
	<c:set var="str1" value="jstlfn"/>
	<c:set var="str2" value="JSTLFN"/>
	<c:set var="tokens" value="1,2,3,4,5,6,7,8,9" />
	
	<h1>Function 태그</h1>
	
	<br>length(map)			: ${fn:length(map) }
	<br>length(str1)		: ${fn:length(str1) }
	<br>toUpperCase(str1)	: ${fn:toUpperCase(str1) }
	<br>toLowerCase(str2)	: ${fn:toLowerCase(str2) }
	<br>substring(str1)		: ${fn:substring(str1, 1, 3) }
	<br>replace(str1)		: ${fn:replace(str1, "f", "^") }
	<br>
	<c:set var="array" value="${fn:split(tokens, ',') }"/>
	join(array, "-")		: ${fn:join(array, "-" )}
</body>
</html>



포기하지 말고 JUST DO! ✔️




출처
https://media.giphy.com/media/dwmNhd5H7YAz6/giphy.gif
https://media.giphy.com/media/3o6Mb9EC7mNqXl9x7y/giphy.gif

0개의 댓글