JSTL(Java Server Page Standard Tag Library) JSP标准标签库,用来替代JSP页面脚本,它与EL(Expression Language)配合可以有效地减少JSP页面中的Java代码。
1.通用基本标签(set,out,remove)
<%--var:变量名,value:变量值--%>
<c:set var="count" value="99" />
<c:out value="${count}"/><hr>
<%--如果变量未被定义值,可声明默认值--%>
<c:out value="${happy}" default="我是默认值"/><hr>
<%--移除值--%>
<c:remove var="count"/>
<c:out value="${count}"/><hr>
输出结果:
2.条件标签
<c:if test="${8>4}">
<h3>你好 2020</h3>
</c:if>
<c:set var="score" value="70"/>
<c:choose>
<c:when test="${score>=90 }">优秀</c:when>
<c:when test="${score>=80 }">良好</c:when>
<c:when test="${score>=70 }">中等</c:when>
<c:when test="${score>=60 }">及格</c:when>
<c:otherwise>不及格</c:otherwise>
</c:choose>
其中要注意两点
- 无<c:else>标签
- choose,when组合即Java中Swith语句的效果
3.循环foreach的使用:
一.简单循环:
<c:forEach var="i" begin="0" end="10" step="2">
${i}<br>
</c:forEach><hr>
二.集合的遍历:
新建TestServlet.java:
package com.qianqian.practice.servlet;
import com.qianqian.practice.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "TestServlet", value = "/test")
public class TestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<User> userList=new ArrayList<>();
userList.add(new User("4567654","李华","7545","man"));
userList.add(new User("5452545","张梁","8775","woman"));
userList.add(new User("6456455","康康","2421","woman"));
userList.add(new User("1312313","小明","5457","man"));
request.setAttribute("userList",userList);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
index.jsp:
<body>
<table border="1" width="30%" bordercolor="black" cellspacing="0" align="center">
<tr>
<th>ID</th>
<th>NAME</th>
<th>PASSWORD</th>
<th>GENDER</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.userId}</td>
<td>${user.userName}</td>
<td>${user.userPassword}</td>
<td>${user.userGender}</td>
</tr>
</c:forEach>
</table>
</body>
结果:
关于EL用法,详见博文:https://blog.csdn.net/qq_42013035/article/details/104079926