JSTL-if, if else 5분안에 정복하기

IF문 : <c:if>

단순 if문을 구성할때 사용할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
<head>
<title><c:if> Tag Example</title>
</head>

<body>
<c:set var = "salary" scope = "session" value = "${2000*2}"/>
<c:if test = "${salary > 2000}">
<p>My salary is: <c:out value = "${salary}"/><p>
</c:if>
</body>
</html>

위의 결과는 아래와 같습니다.

1
My salary is: 4000

IF ~ ELSE 문 : <c:choose>

java에서 많이 사용하는 if~else 문의 경우 jstl에서는 <c:choose>를 이용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
<head>
<title><c:choose> Tag Example</title>
</head>

<body>
<c:set var = "salary" scope = "session" value = "${2000*2}"/>
<p>Your salary is : <c:out value = "${salary}"/></p>
<c:choose>

<c:when test = "${salary <= 0}">
Salary is very low to survive.
</c:when>

<c:when test = "${salary > 1000}">
Salary is very good.
</c:when>

<c:otherwise>
No comment sir...
</c:otherwise>
</c:choose>

</body>
</html>
1
2
Your salary is : 4000
Salary is very good.

비교기호 : eq, ne, empty, not empty

if문을 사용할때에는 반드시 값과 비교를 해서 결과를 얻기때문에, jstl에서는 eq, ne와 같은 비교기호를 사용할 수 있습니다.

  1. eq (==)
    동일한 값인지 확인하기 위해 사용합니다.
1
2
3
4
5
6
7
8
9
10
11
<c:if test="${name == '둘리'}">

<c:if test="${name eq '둘리'}">

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

<c:if test="${name eq null}">

<c:if test="${age == 7}">

<c:if test="${age eq 7}">
  1. ne (!=)
    동일하지 않은 값을 확인하기 위해 사용합니다.
1
2
3
4
5
6
7
<c:if test="${name != '둘리'}">

<c:if test="${name ne '둘리'}">

<c:if test="${age != 5}">

<c:if test="${age ne 5}">
  1. empty (== null)
    비교하는 값이 null 인지 확인할때 사용합니다.
    null이 아닌경우를 표현할때는 !emptynot empty 표현합니다.
1
2
3
4
5
<c:if test="${empty name}">

<c:if test="${not empty name}">

<c:if test="${!empty name}">

논리 연산자

  • and && : 모두 참일때 참이 됩니다.
1
2
3
<c:if test="${a > b and c < d}">

<c:if test="${a > b && c < d}">
  • or || : 둘중 하나라도 참이면 참이 됩니다.
1
2
3
<c:if test="${a > b or c < d}">

<c:if test="${a > b || c < d}">
  • not ! : 논리를 반전합니다. 참이면 거짓으로 변경되고, 거짓이면 참으로 변환됩니다.
1
2
3
<c:if test="${not a == ''}">

<c:if test="${! a == ''}">

Reference

Share