EL表达式
目的是替换JSP页面中的复杂代码。
语法:
${变量名}
在el1.jsp 中提交表单到ElServlet
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>表单提交</title>
</head>
<body>
<form action="/ElServlet" method="post">
姓名: <input type="text" name="username"> <br>
年龄: <input type="number" name="age">
<input type="submit" value="提交">
</form>
</body>
</html>
在 ElServlet 中获取到 el1.jsp中提交的参数,然后转发到el2.jsp中
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String age = request.getParameter("age");
request.setAttribute("username", username);
request.setAttribute("age", age);
request.getRequestDispatcher("/el/el2.jsp").forward(request, response);
}
在el2中使用 el表达式 拿到转发过来的参数
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>使用Jsp查看</title>
</head>
<body>
姓名: ${username} <br>
年龄: ${age}
</body>
</html>
JSTL
- JSTL标准标签库
- 与 el表达式关系
通常会与el表达式合作实现JSP页面的编码. (在jsp页面中尽量不要书写java代码) - jstl页面开发准备
导入 jstl.jar包
在jsp页面添加taglib指令 <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="c" %>
通用标签
<%-- set标签: 将值存储到范围为scope的变量中
var - value 类似一个键值对, 表示的意思是 : 在 request的范围内,存储一个username = "张么子"的变量--%>
<c:set var="username" value="张么子" scope="request"/>
<%-- out标签 :将结果输出显示 --%>
<c:out value="value"/>
<%-- remove标签 , 删除指定域内数据 --%>
<c:remove var="username" scope="session"/>
if标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>jstl常用标签</title>
</head>
<body>
<c:set var="age" value="12" scope="request"/>
<%-- 使用 if 标签 --%>
<c:if test="${age==12}">
您的年龄是12岁
</c:if>
Hello
</body>
</html>
choose标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>jstl常用标签</title>
</head>
<body>
<c:set var="age" value="12" scope="request"/>
<c:choose>
<c:when test="${age==12}">
你的年龄是12岁
</c:when>
<c:otherwise>
你的年龄不是12岁
</c:otherwise>
</c:choose>
</body>
</html>
迭代标签
<c:forEach items="${list}" var="Map">
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>JSTL + EL</title>
</head>
<body>
<table border="1px" cellspacing="0">
<tr>
<td>商品名</td>
<td>价格</td>
</tr>
<c:forEach items="${list}" var="Map">
<tr>
<td> ${Map.name}</td>
<td> ${Map.price}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
网友评论