一、EL表达式
1、产生原因
- 在JSP页面里面使用了大量的Java代码,在JSP2.0开发规范里面建议尽量不要在JSP页面中使用Java代码,这样会导致后期的维护工作非常麻烦
- 使用EL表达式和JSTL标签去代替Java代码
- EL表达式和JSTL标签在JSP转换成Java文件后,本质都会翻译成也对应的大段Java代码
2、概述
Expression Language表达式语言:通过这个表达式能替换掉java代码(输出)来获取数据(从域中获取数据) <%= %>
注意:
- EL表达式只能获取数据不能设置值
- EL表达式没有找到数据,显示空白
3、语法
${表达式}
4、使用案例
4.1 获取普通的单值数据
- ${域对象中的值}
- ${pageScope[‘域对象中的值’]}
- ${pageScope.域对象中的值} 等价于:pageContext.getAttribute(“name”);
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用EL表达式获取数据</title>
</head>
<body>
<h3>EL表达式获取普通单值(域对象)</h3>
<!-- 1.设置值(今天使用java代码,以后都是从java代码进行页面跳转) -->
<%
//pageContext.setAttribute("book", "西游记",pageContext.PAGE_SCOPE);
pageContext.setAttribute("book", "红楼梦",pageContext.REQUEST_SCOPE);
//pageContext.setAttribute("book", "三国演义",pageContext.SESSION_SCOPE);
//pageContext.setAttribute("book", "水浒传",pageContext.APPLICATION_SCOPE);
%>
<!-- 2.获取值 -->
${requestScope.book } <!-- 从指定的域范围获取单值数据(给定名称就可以获得值),如果没有获取到数据,显示白板 -->
${requestScope['book'] }
${requestScope["book"] }
<!-- 上面的代码等价于下面的代码,EL的出现就是为了取代输出脚本,如果没有获取到数据, 返回null -->
<%=pageContext.getAttribute("book",pageContext.REQUEST_SCOPE) %>
<hr>
<!-- 使用findAttribute方法 -->
<%=pageContext.findAttribute("book") %>
<!-- 使用EL获取数据,也不不指定域:这种方式使用最多!!!!-->
${book}
</body>
</html>
4.2 获取数组的数据
- ${域对象中的值[下标] }
<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>EL表达式获取数据</title>
</head>
<body>
<h3>EL获取数组中的数据</h3>
<!-- 1.设置值 -->
<%
//准备数组
String[] city={"北京","南京","天津","东京"};
//将数据保存到域对象
pageContext.setAttribute("city", city);
%>
<!-- 2.获取值,东京 单值获取数据可以使用[]也可以使用.;数组只能使用[]-->
${city[3] }
</body>
</html>
4.3 获取List集合的数据
- ${域对象中的值[下标] }
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>EL表达式获取数据</title>
</head>
<body>
<h3>EL获取List集合中的数据</h3>
<!-- 1.设置值 -->
<%
//准备集合
ArrayList<String> list = new ArrayList<String>();
//向集合中添加数据
list.add(0, "北京");
list.add(1, "南京");
list.add(2, "天津");
list.add(3, "东京");
//将list集合添加域对象
pageContext.setAttribute("list", list);
%>
<!-- 2.获取值 -->
${list[1] }
</body>
</html>
4.4 获取Map集合的数据
- ${域对象中的值.key}
- ${域对象中的值['key'] }
<%@page import="java.util.HashMap"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>EL表达式获取数据</title>
</head>
<body>
<h3>EL获取Map集合中的数据</h3>
<!-- 1.设置值 -->
<%
//准备集合
HashMap<String,String> map = new HashMap<String,String>();
//向map集合中添加数据
map.put("username","芬美丽");
map.put("age","18");
map.put("password","001");
map.put("desc","大哥");
//将map添加到域对象
pageContext.setAttribute("map", map);
%>
<!-- 2.获取值 -->
${map.username }
${map['username'] }
</body>
</html>
4.5 获取对象的数据
- ${域对象中的值.属性名}
- ${域对象中的值['属性名'] }
package com.itheima.domain;
public class User {
private String username;
private String password;
public User() {
super();
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<%@page import="java.util.ArrayList"%>
<%@page import="com.itheima.domain.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>EL获取数据</title>
</head>
<body>
<h3>EL获取对象中的数据</h3>
<!-- 1.设置值 -->
<%
//创建一个对象
User user = new User("张三","123");
//将user保存域对象
pageContext.setAttribute("user", user);
%>
<!-- 2.获取值 -->
${user.password }
${user['password'] }
</body>
</html>
4.6 获取对象集合的数据
${域对象中的值[下标].属性名}
<%@page import="java.util.ArrayList"%>
<%@page import="com.itheima.domain.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>EL获取数据</title>
</head>
<body>
<h3>EL获取对象集合数据</h3>
<%
//创建多个对象
User user1 = new User("张三","123");
User user2 = new User("李四","456");
User user3 = new User("王五","789");
User user4 = new User("麻婆","369");
//准备一个集合
ArrayList<User> list = new ArrayList<User>();
//将对象放入list集合
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
//将list集合保存域对象
pageContext.setAttribute("list", list);
%>
<!-- 2.获取值:369 -->
${list[3].password }
${list[3]["password"] }
<!--
总结:EL表达式获取数据会使用的方式
数组、list集合:只能使用[]
单值、map集合、对象:既能使用[],也能使用. 【如果名称key的值里面包含了特殊符号,那么只能使用[]】
对象集合:现获取集合(你根据上面的总结来选取获取方式,然后获取对象)
-->
</body>
</html>
<h3>演示只能使用[]不能使用.的单值获取数据的情形</h3>
${header.Accept } <!-- 可以使用.也可以使用[] -->
<hr>
${header.User-Agent } <!-- 得到的是0,作运算了,不能使用.(有特殊符号) -->
${header['User-Agent'] }
.和[]的区别
- 如果是数组和list集合,那么必须使用[] 【单列】
- 如果Map集合和对象可以使用[],还可以使用. 【双列】
- 如果是特殊字符,必须使用[]
二、JSTL标签库
jstl它是取代<% %>的,但是一直没有全部替换掉
1、使用步骤
1.1 导入jar包
1.2 引入标签库
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
2、JSTL中的标签库
2.1 if
test:条件(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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSTL标签:判断</title>
</head>
<body>
<h3>if标签</h3>
<!-- 设置值 -->
<c:set var="count" value="5"></c:set>
<!-- 使用if标签进行判断 -->
<c:if test="${count==5 }">
你可以看到我了……
</c:if>
</body>
</html>
2.2 set
- var:变量的名称
- value:变量的值
2.3 out
- value:变量的名称
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSTL标签</title>
</head>
<body>
<h3>JSTL标签_set和out:了解即可</h3>
<!-- 1.设置值 -->
<!--
set:设置值
var:变量的名称
value:变量的值
-->
<c:set var="count" value="10"></c:set>
<!-- 2.使用jstl标签取代代码片段脚本 -->
<!--
呕吐:获取值
value:变量的名称
-->
<c:out value="${count }"></c:out>
</body>
</html>
2.4 choose【重要】
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSTL标签:判断</title>
</head>
<body>
<h3>choose标签</h3>
<!-- 1.设置值 -->
<c:set var="count" value="3"></c:set>
<!--
使用choose标签做判断:
跟java的if(){}else if(){} else{}功能类似
when:相当于 if(){}else if(){}
otherwise:相当于else{}
-->
<c:choose>
<c:when test="${count==3 }">
你答对了
</c:when>
<c:when test="${count==5 }">
好样的
</c:when>
<c:otherwise>
你真傻
</c:otherwise>
</c:choose>
</body>
</html>
2.5 foreach【重要】
- items:被遍历的对象
- var:被遍历之后的单个对象的名称
- begin:起始索引(从0开始)
- end:结束索引
- varStatus:被遍历之后对象的信息都保存在这个对象中(是否一个,是否最后一个,编号,索引)
- index:索引(当前元素所处位置的索引值)
- first:是否第一个
- last:是否最后一个
- count:编号,永远从1开始 【开发中最常用】
- step:步长(默认值为1)
<%@page import="java.util.ArrayList"%>
<%@page import="com.itheima.domain.User"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSTL标签</title>
</head>
<body>
<h3>foreach遍历标签</h3>
<%
//创建多个对象
User user1 = new User("tom","123");
User user2 = new User("jerry","111");
User user3 = new User("老宋","厉害了");
User user4 = new User("老王","out了");
User user5 = new User("苏秦","奴婢");
User user6 = new User("二叔","超帅");
User user7 = new User("天明","好久不见");
User user8 = new User("端木蓉","躺了好几年");
//准备一个集合
ArrayList<User> list = new ArrayList<User>();
//将对象放入list集合
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
list.add(user6);
list.add(user7);
list.add(user8);
//将list集合保存域对象
pageContext.setAttribute("list", list);
%>
<table border="1px" width="50%" align="center">
<tr>
<th>编号</th>
<th>索引</th>
<th>姓名</th>
<th>密码</th>
<th>是否第一个</th>
<th>是否最后一个</th>
</tr>
<!-- 显示数据 -->
<!--
遍历标签的属性介绍
items:被遍历的对象
var:被遍历之后的单个对象的名称
begin:起始索引(从0开始)
end:结束索引
varStatus:被遍历之后对象的信息都保存在这个对象中(是否一个,是否最后一个,编号,索引)
index:索引(当前元素所处位置的索引值)
first:是否第一个
last:是否最后一个
count:编号,永远从1开始 【开发中最常用】
step:步长(默认值为1)
-->
<c:if test="${not empty list }">
<c:forEach items="${list}" var="user" begin="0" end="7" varStatus="vs" step="3">
<tr align="center">
<td>${vs.count }</td>
<td>${vs.index }</td>
<td>${user.username }</td>
<td>${user.password }</td>
<td>${vs.first }</td>
<td>${vs.last }</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
三、案例
package com.itheima.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 处理post请求中文乱码问题
request.setCharacterEncoding("utf-8");
// 处理响应的中文乱码问题
response.setContentType("text/html;charset=utf-8");
ProductService service = new ProductService();
try {
List<Product> products = service.findAll();
request.setAttribute("lists", products);
request.getRequestDispatcher("list.jsp").forward(request, response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.itheima.service;
import java.sql.SQLException;
import java.util.List;
import com.itheima.dao.ProductDao;
import com.itheima.domain.Product;
public class ProductService {
public List<Product> findAll() throws SQLException {
ProductDao dao = new ProductDao();
return dao.findAll();
}
}
package com.itheima.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.domain.Product;
import com.itheima.utils.C3P0Utils;
public class ProductDao {
public List<Product> findAll() throws SQLException {
// 1.获得QueryRunner核心对象
QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
// 2.编写SQL语句
String sql = "select * from product";
// 3.执行查询操作
return qr.query(sql, new BeanListHandler<>(Product.class));
}
}
<%@ 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>展示商品信息</title>
</head>
<body>
<table border="1px" width="65%" align="center">
<tr>
<th>编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品描述</th>
</tr>
<c:if test="${not empty lists }">
<c:forEach items="${lists }" var="product" varStatus="vs">
<tr>
<td>${vs.count }</td>
<td>${product.pname }</td>
<td>${product.price }</td>
<td>${product.pdesc }</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>