JSP Scriptlet (`<% ... %>`) 內直接寫標準 Java `if-else`,但**大括號 `{}` 強烈建議恆加**,避免 HTML 穿插導致邏輯錯誤。
<%
int score = 85;
if (score >= 60) {
out.println("及格");
}
%>
<%
int age = 17;
if (age >= 18) {
out.println("成年");
} else {
out.println("未成年");
}
%>
<%
String grade = "B";
if ("A".equals(grade)) {
out.println("優秀");
} else if ("B".equals(grade)) {
out.println("良好");
} else if ("C".equals(grade)) {
out.println("及格");
} else {
out.println("需加強");
}
%>
字串比較必用 `equals()`**,不可用 `==` (比較引用)。
<%
int x = 10, y = 5;
if (x > 0) {
if (y > 0) {
out.println("第一象限");
} else {
out.println("第四象限");
}
}
%>
<%= (score >= 60) ? "通過" : "不通過" %>
適合簡單輸出,邏輯複雜請用 Scriptlet。
**不寫 Java 程式碼**,純標籤,可讀性更強:
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<c:choose>
<c:when test="${score >= 90}">優秀</c:when>
<c:when test="${score >= 80}">良好</c:when>
<c:when test="${score >= 60}">及格</c:when>
<c:otherwise>不及格</c:otherwise>
</c:choose>
<c:if test="${not empty userList}">有資料</c:if>
${user.age >= 18 ? '成年' : '未成年'}