JSP

부트캠프47일 (EL , JSTL)

동곤일상 2025. 4. 9. 17:48
반응형

1) 표현언어(EL)

1-1)EL의 연산

1-2) 사용 예

 

2)JSTL

2-1) JSTL사용을 위해 라이브러리 다운로드

2-2)사용(set,out,remove)

2-3) if , choose

2-4) 반복문 forEach

 

3) 예제

 


1)표현언어 (EL)

\jspStudy\src\main\webapp\ex13_EL\ex1_EL.jsp

<%@ 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>
<!-- 
	1.request : 요청객체(브라우저에서 전달되는 요청정보 저장)
	2.response : 응답객체(브라우저로 전달하는 정보 저장)
	3.pageContext : 현재페이지의 정보저장하고있는 객체
	4.session : 브라우저의 상태정보를 저장할수있는 객체
	5.applcation : 웹 어플리케이션(프로젝트)정보 저장 객체
 -->
<%
	String tel = "010-1111-2222";
	pageContext.setAttribute("tel", tel);
	pageContext.setAttribute("test", "pageContext의 test속성");
	request.setAttribute("test", "request의 test속성");
	session.setAttribute("test", "session의 test속성");
	application.setAttribute("test", "application의 test속성");
	String name = "홍길동";
%>
<h3>JSP의 스크립트를 이용해 파라미터와 속성값 출력하기</h3>
pageContext tel속성값 : <%=pageContext.getAttribute("tel") %> <br>
pageContext test속성값 : <%=pageContext.getAttribute("test") %><br>
request test속성값 : <%=request.getAttribute("test") %><br>
session test속성값 : <%=session.getAttribute("test") %><br>
application test속성값 : <%=application.getAttribute("test") %><br>
name 변수값 : <%= name %><br>
id파라미터 : <%= request.getParameter("id") %><br>
없는속성 : <%= request.getAttribute("noAttr") %><br>
없는 파라미터 : <%=request.getParameter("noParam") %>

<h3>JSP 의 EL을 이용해 파라미터와 속성값 출력하기</h3>
pageContext tel속성값 : ${pageScope.tel}<br> 
pageContext test속성값 : ${pageScope.test}<br> 
request test속성값 : ${requestScope.test}<br> 
session test속성값 : ${sessionScope.test}<br> 
application test속성값 : ${applicationScope.test}<br>
name 변수값 : EL방식으로 출력할방법이없음 <br>  
id 파라미터 : ${param.id}<br> 
없는속성 : ${requestScope.noAttr}<br>
없는 파라미터 : ${param.noParam}<br>
<!-- pageScope : pageContext에 저장된속성을 참조시 사용 -->
<!-- ${값} -->


<h3>영역을 표시해 속성 출력</h3>
<!--  \ 뒤에 적은것들은 그대로 출력이됨 -->
\${test} : ${test}<br>
\${pageScope.test} :${pageScope.test}<br> 
\${requestScope.test} :${requestScope.test}<br> 
\${sessionScope.test} :${sessionScope.test}<br> 
\${applicationScope.test} :${applicationScope.test}<br>
\${param.id} : ${param.id}<br>
\${requestScope.noAttr} : ${requestScope.noAttr}<br>
\${param.noParam} : ${param.noParam}<br>

</body>
</html>


${test} : 영역담당객체에 등록된 속성중 이름이 test인 속성값 출력
우선순위
1.page영역에등록된 pageScope.test 속성값
2.1번이없으면  , request영역에등록된 pageScope.test
3.2번이없으면 , session영역에등록된 sessionScope.test
4.3번이없으면 , application영역에등록된 applicationScope.test
5.1~4번이없으면 공백을 출력

${영역객체.A} : 영역객체에 등록된속성중 이름이A인 속성값출력
1.해당영역에 A속성이없다면 공백을 출력 

 

 

1-1) EL의 연산

 

/jspStudy/src/main/webapp/ex13_EL/ex2_EL.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL에서 연산자이용하기</title>
</head>
<body>
\${5+7} : ${5+7} <br>
\${8-3} : ${8-3} <br>
\${8/3} : ${8/3} <br>
\${8 div 3} : ${8 div 3} <br>
\${8 % 3} : ${8 % 3} <br>
\${10==9} : ${10==9} <br>
\${10 eq 9} : ${10 eq 9} <br>
\${10!=9} : ${10!=9} <br>
\${10 ne 9} : ${10 ne 9} <br>

\${10>=9} : ${10>=9} <br>
\${10 ge 9} : ${10 ge 9} <br>

\${10 > 9} : ${10 > 9} <br>
\${10 gt 9} : ${10 gt 9} <br>

\${10<=9} : ${10<=9} <br>
\${10 le 9} : ${10 le 9} <br>
\${10<9} : ${10<9} <br>
\${10 lt 9} : ${10 lt 9} <br>
\${5+4==8?8:10} : ${5+4==8?8:10}<br>
\${10}=${10 }<br>
\${'EL의 상수표현' }=${'EL의 상수표현' }<br>
 

</body>
</html>

 

 

 

1-2) 사용예

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!--  
	prefix = "test" : 접두어가 test인 태그(함수)인 경우
	
	uri="/ELFunctions" : uri가 /ELFunctions인 파일 참조
	/WEB-INF/의 하위폴더에서 <uri>/ELFunctions</uri> 형태로
					설정된파일 검색=> /tlds/el_function.tld파일선택
 -->
<%@ taglib prefix="test" uri="/ELFunctions"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post"><!-- action속성X => 현재페이지다시호출 -->
x : <input type="text" name="x" value="${param.x}"><br>
y : <input type="text" name="y" value="${param.y}"><br>
					<!--${param.a} : 파라미터속성 a -->
<input type="submit" value="더하기">
</form>
<p>
합계 : ${test:add(param.x,param.y) }<br>
</body>

</html>

 

el_function.tld
0.00MB

다음과같은 tld파일을 다운로드받아

WEB-INF 하위에 폴더를 만들어 보관해두자

jspStudy\src\main\webapp\WEB-INF\tlds\el_function.tld

 

 

 JspDong\jspStudy\src\main\java\ex13\el\Compute.java

(다음과같은 경로에 이 파일을 만들어두자(add메서드, contains메서드사용가능)

package ex13.el;

import java.util.Arrays;
import java.util.List;

public class Compute {
	public static int add(String x, String y) { 
		//add메서드
		   try {
			   int a = Integer.parseInt(x);
			   int b = Integer.parseInt(y);
			   return a + b;
		   } catch (Exception e) {}
		   return 0;
	   }
	   public static boolean contains(String[] arr,String str) {
		   try {
			   List<String> list = Arrays.asList(arr);
			   return list.contains(str);
		   } catch (Exception e) {e.printStackTrace();}
		   return false;
	   }

}

 

 

 


 

2) JSTL

2-1) JSTL사용을 위해 라이브러리 다운로드

https://tomcat.apache.org/download-taglibs.cgi

다음과같은 링크에 접속 후 4개의jar파일 다운로드

다운로드한 후

 

WEB-INF 하위의 lib폴더에 붙여넣어주자

 

2-2) 사용(set,out,remove)

라이브러리 존재 (set remove out등의 함수정보)

set태그:  session영역의  test이름의 속성등록 /  값:'Hello JSTL' 
scope 속성 생략시   기본값 : page -->


 out태그 : 속성값 화면에출력  EL보다 보안성이 높음 

  excape xml : &lt; script &gt; 와같이 바꿔줌

 
 remove : 등록된 속성 제거-->

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
//라이브러리를 위한 taglib
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!--  jspStudy\src\main\webapp\ex14_jstl\ex1_core.jsp -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %> 
<!--c 호출 시  http://java.sun.com/jsp/jstl/core의 내용을 참고해 -->
<!--위에서 보여준 라이브러리에 존재할것임-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>속성관련 태그 : set , remove , out 태그</h3>

<!-- session.setAttribute("test","Hello JSTL");와 같은느낌 -->

<c:set var="test" value="${'Hello JSTL'}" scope="session" />
test 속성 : ${sessionScope.test}<br>
test 속성 : <c:out value="${test}" /><br>
test 속성 : ${test}<br>
<c:remove var="test" />
test 속성 : ${test}<br>

</body>
</html>

 

 

2-3) 사용(if  , choose)

core태그의 if에는 else가 없다

 

대신

 

choose문을 사용해서

when(if)

otherwise(else) 이용가능

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>core태그 : if, choose</title>
</head>
<body>
<h3>조건문관련태그 : if, choose 태그</h3>
<!-- else는 없음 test속성이 무조건있어야함 -->
<c:if test="${5<10}">
	<h4>5는10보다 작다(core태그이용)</h4>
</c:if>

<%if(5<10){ %>
	<h4>5는10보다작다(스크립트 릿 이용)</h4>
<%} %> 

<!-- choose 조건문 when(if)과 otherwise(else) -->
<c:choose>
	<c:when test="${5+10==25 }">
		<h4>5+10은 25다</h4>
	</c:when>
	<c:when test="${5+10==15 }">
		<h4>5+10은 15다</h4>
	</c:when>
	<c:when test="${5+10==510 }">
		<h4>5+10은 510이다</h4>
	</c:when>
	<c:otherwise> <!-- else와 같음 -->
		<h4>5+10은 모른다</h4>
	</c:otherwise>
</c:choose>
</body>
</html>

 

2-4) 반복문 (forEach)

 

core태그의 forEach사용법

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

 

<c:forEach var="변수명" begin="시작숫자" end="끝숫자">

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>
<!-- JSTL태그 사용을위해서 항상 taglib를 적어야함 -->    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jstl core태그 : forEach</title>
</head>
<body>
<h3>반복관련태그 : forEach</h3>
<h4>1에서10까지 숫자출력해보기</h4>
<!-- for(int i =1 ; i<=10 ; i++)과 같음 -->
<c:forEach var="i" begin="1" end="10">
${i}&nbsp;,&nbsp;	
</c:forEach>

<h4>1부터10까지 홀수만 출력하자</h4>
<!-- for(int i=1 ; i<=10 ; i+=2) -->
<c:forEach var="i" begin="1" end="10" step="2">
${i}&nbsp;,&nbsp;	
</c:forEach>

<h4>1부터10까지 홀수만 출력하자2</h4>
<!-- for(int i=1 ; i<=10 ; i+=2) -->
<c:forEach var="i" begin="1" end="10" >
	<c:if test="${i%2==1}">
		${i}&nbsp;,&nbsp;
	</c:if>
</c:forEach>

<h4>1부터10까지 짝수만 출력하자</h4>
<!-- for(int i=1 ; i<=10 ; i+=2) -->
<c:forEach var="i" begin="1" end="10" >
	<c:if test="${i%2==0}">
		${i}&nbsp;,&nbsp;
	</c:if>
</c:forEach>

<h4>1부터10까지의 합 출력</h4>
<c:forEach var="i" begin="1" end="10">
	<c:set var="sum" value="${sum+i}"/>
</c:forEach>
1부터10까지의 합 : ${sum}<br>

 <!-- 변수의 사용이끝났으므로 변수 초기화 (다른변수를 만들어서 사용해도 상관없음)-->
 <!-- c:set으로 생성되는 함수는 page함수이므로 다른페이지에 영향은없음 -->
<c:set var="sum" value="${0}"/>

<h4>1부터10까지의 짝수 합 출력</h4>
<c:forEach var="i" begin="2" end="10" step="2">
	<c:set var="sum" value="${sum+i}"/>
</c:forEach>
1부터10까지의 짝수 합 : ${sum}<br>

<!-- 변수의 사용이끝났으므로 변수 초기화(다른변수를 만들어서 사용해도 상관없음) -->
<c:set var="sum" value="${0}"/>

<h4>1부터10까지의 홀수 합 출력</h4>
<c:forEach var="i" begin="1" end="10">
	<c:if test="${i%2==1}">
		<c:set var="sum" value="${sum+i}"/>
	</c:if>
</c:forEach>
1부터10까지의 짝수 합 : ${sum}<br>


<h3>forEach태그를 이용해 구구단</h3>
<c:forEach var="i" begin="2" end="9">
	<h4>${i}단</h4>
	<c:forEach var="j" begin="2" end="9">
	   ${i} * ${j} = ${i*j}&nbsp;
	</c:forEach><br>
</c:forEach>
</body>
</html>

3) 예제

문제1)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%-- /jspstudy2/src/main/webapp/test/test1.jsp --%>
<%@ taglib prefix="test" uri="/ELFunctions"%>    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>  <!-- 태그라이브러리추가 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<title>두개의 파라미터값을 계산하기</title>
</head>
<body>
<form method="post" >
  x:<input type="text" name="x" value="${param.x}"><br>
  y:<input type="text" name="y" value="${param.y}">
   <input type="submit" value="더하기">  
</form>
<c:set var="test" value="${param.x + param.y}"/>
<c:out value="${test}"/>
<h4>if태그를 이용하기</h4>
<c:if test="${test<0}">
	<c:out value="${test}은 음수입니다"/>
</c:if>
<c:if test="${test>=0}">
	<c:out value="${test}은 양수입니다"/>
</c:if>
<h4>choose태그이용하기</h4>
<c:choose>
	<c:when test="${test<0}">
		${test}는 음수다
	</c:when>
	<c:otherwise>
		${test}는 양수다
	</c:otherwise>
</c:choose>


</body>
</html>

 


문제2)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<%-- /jspstudy2/src/main/webapp/test/test2.jsp --%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>입력된 수까지의 합 구하기</title>
</head>
<body>
<form method="post">
  숫자:<input type="text" name="num" value="${param.num}">
   <input type="submit" value="숫자까지의 합 구하기">  
</form>
<c:forEach var="i" begin="1" end="${param.num}">
	<c:set var="sum" value="${sum+i}"/>
</c:forEach>
<c:out value="${sum}"/>

<h4>if태그이용해 짝수홀수출력</h4>
<c:if test="${sum%2==0}">
	<c:out value="${sum}은 짝수"/>
</c:if>
<c:if test="${sum%2==1}">
	<c:out value="${sum}은 홀수"/>
</c:if>

<h4>choose태그 이용해 짝수홀수출력</h4>
<c:choose>
	<c:when test="${sum%2==0}">
		<c:out value="${sum}은 짝수"/>
	</c:when>
	<c:otherwise>
		<c:out value="${sum}은 홀수"/>
	</c:otherwise>

</c:choose>

</body>
</html>

 


문제3)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title>jstl을 이용한 간단한 연산</title>
</head>
<body>
<form method="post" name="f">
  x:<input type="text" name="x" value="${param.x}" size="5">
  <select name="op">
  <!-- 선택된값을 selected 처리해줌(선택) -->
     <option value="+" >+</option>
     <option value="-" >-</option>
     <option value="*" >*</option>
     <option value="/">/</option>
  </select>
  y:<input type="text" name="y" value="${param.y}" size="5">
  <input type="submit" value="=">
  <script>
  	var op = '${param.op}';
  	if(op==''){
  		op = '+';
  	}
  	document.f.op.value = op;
  </script>
</form>
	<c:if test="${param.op eq '+'}">
		<h4>${param.x}+${param.y}=${param.x+param.y}</h4>
	</c:if>
	<c:if test="${param.op eq '-'}">
		<h4>${param.x}-${param.y}=${param.x-param.y}</h4>
	</c:if>
	<c:if test="${param.op eq '*'}">
		<h4>${param.x}*${param.y}=${param.x*param.y}</h4>
	</c:if>
	<c:if test="${param.op eq '/'}">
		<h4>${param.x}/${param.y}=${param.x/param.y}</h4>
	</c:if>


  </body></html>

 


문제4)

 

<%@page import="java.time.LocalDate"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<title>Insert title here</title></head>
<body>

<form action="test4.jsp" method="post">

   이름:<input type="text" name="name"><br>
   나이:<input type="text" name="age"><br>
   성별:<input type="radio" name="gender" value="1">남
     <input type="radio" name="gender" value="2">여<br>
 출생연도 : <select name="year">
 <c:forEach var="i" begin="1980" end="2025">
 <option>${i}</option>
 </c:forEach>
 </select><br>
  <input type="submit" value="전송"></form>
  
</body></html>
<%@page import="java.time.LocalDate"%>
<%@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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8"); 
LocalDate ld = LocalDate.now();
int now = ld.getYear();
pageContext.setAttribute("dt", now);  //page(같은페이지)영역에 속성을 지정해준다
%>
이름 : ${param.name}<br>
나이 : ${param.age}<br>
성별 : 
<c:choose>
	<c:when test="${param.gender eq 1}">
		남 <!-- value가 1이면 남 출력 -->
	</c:when>
	<c:otherwise>
		여<!-- value가 1이아니면 여 출력 -->
	</c:otherwise>
</c:choose>
<br>
출생년도 : ${param.year}<br>
만나이 : ${dt - param.year}
<!-- 만나이 : ${pageScope.dt - param.year} 와 같은뜻--> 


</body>
</html>