JSTL的好帮手 EL表达式
1、EL (Expression Language)
-经常与JSTL配合使用,使得JSP页面更直观,写法更简单
-普通写法:
<%= session.getValue("name") %>
-EL表达式写法:
<c:out value="${sessionScope.name}">
2、EL表达式的基本格式
使用美元 “$” 定界,内容包括在花括号 “{ }” 中;
- "${表达式}"
3、"." 与 “[ ]” 运算符
3.1、通常情况下两者是通用的
${user.sex}
${user[ "sex" ]}
3.2、" [ ] " 还可以用来进行集合元素中的定位
${bookList[0].price}
3.3、除了两种情况、两者不可混用
3.3.1、包含特殊字符
${user[ "first-name" ]}
3.3.2、通过变量动态取值
1、param 可以是name or sex or others
${user.name} or ${user.sex} or ...
4、EL变量
JSP内置对象对应的EL名称
Page:PageScope
Request:RequestScope
Session:SessionScope
Application:ApplicationScope
如果未做限制,寻找顺序Page->Request->Session->Application
5、EL 自动类型转换
5.1、要获取文本框中的值,我们需要做类型转换
//正常jsp代码
String str_count = request.getParameter("count");
int count = Integer.parseInt(str_count);
count = count + 20;
//EL 自动进行类型转换
${param.count + 20}
6、EL 隐式对象
7、EL 运算符
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FirstDemo</title>
</head>
<body>
<% String username="zhangsan"; request.setAttribute("username", username);%>
<c:out value="This is our first JSTL demo!"></c:out><br/>
<c:out value="${ username }"></c:out><br/>
<c:out value="${empty username }"></c:out><!-- empty 判断变量是否为空,如果是空返回true,如果不是空返回false -->
</body>
</html>