一、优化
(1)EL表达式
EL表达式可以在JSP界面简化域对象的getAttribute()方法
<%
Integer name = (Integer) request.getAttribute("id");
%>
<%=name%>
// 等价
${id}
对于自定义的类对象${person.name}
相当于访问getName()方法,而不是name属性。
然而可能会出现key同名的情况,那么默认优先级与生命周期相反,越局部的域对象的优先级越高。还可以指定作用域进行查找
${pageScope.id}
${requestScope.id}
${sessionScope.id}
${applicationScope.id}
(2)JSTL
JSP标准标签库,开发人员可以利用这些标签取代JSP页面上的Java代码,从而提高程序的可读性,降低程序的维护难度。
2.1 导入包
使用JSTL之前需要导入,第一步:把所需要的包放入WEB-INF中新建好的lib文件夹中
第二步:按照下图所示导入
第三步:在JSP开头位置输入
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
2.1 常用标签使用
foreach:遍历域对象
@WebServlet("/user")
public class Test1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("张三", 10));
people.add(new Person("李四", 20));
people.add(new Person("王五", 30));
req.setAttribute("lists", people);
req.getRequestDispatcher("JSTL.jsp").forward(req, resp);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>JSTL使用</title>
</head>
<body>
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
// 遍历lists,取list
<c:forEach items="${lists}" var="list">
<tr>
<td>${list.name}</td>
<td>${list.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
items=列表
var=各个成员
begin=开始
end=截止
step=步长
varStatus=标识
set:向域对象中添加数据
<body>
<%
Person people = new Person("lili", 15);
request.setAttribute("people", people);
%>
<c:set target="${people}" property="age" value="20" ></c:set>
${people}
</body>
out:输出域对象中数据
<body>
<c:set var="num" value="123" ></c:set>
<c:out value="${num}" default="没有值"></c:out>
</body>
remove:删除域对象的数据
<body>
<c:set var="num" value="123" scope="page"></c:set>
<c:remove var="num" scope="page"></c:remove>
<c:out value="${num}" default="不存在"></c:out>
</body>
catch:异常捕获
<body>
<c:catch var="error">
<%
int a=5/0;
%>
</c:catch>
${error}
</body>
if / choose 条件标签
<body>
<c:set var="num1" value="30" scope="page"></c:set>
<c:set var="num2" value="20" scope="page"></c:set>
<c:if test="${num1==num2}">相等</c:if>
<c:if test="${num1!=num2}">不相等</c:if>
<hr/>
<c:choose>
<c:when test="${num1==num2}">相等</c:when>
<c:otherwise>不相等</c:otherwise>
</c:choose>
</body>