EL表达式的学习

一、EL表达式

EL(Expression Language)提供了在 JSP 中简化表达式的方法,让Jsp的代码更加简化.

语法:${expression}

el表达式的隐含对象包括:pageScope,requestScope,sessionScope,applicationScope ${message} EL表达式会依次(从小到大)到pageScope,requestScope,sessionScope,applicationScope中寻找,直到找到为止。 如果写成${requestScope.message}的形式,将会缩小范围只在requestScope中查找message。

常见使用场景:取出request中封装的数据 String或基本数据类型 javabean List<String或基本数据类型> List Map

1.EL表达式取出request中的String和基本数据类型 request.setAttribute("name", "孙悟空"); request.setAttribute("age", 500); request.getRequestDispatcher("test.jsp").forward(request, response); name=${name }, age=${age }

2.EL表达式取出request中的javabean // 设置javabean request.setAttribute("person1", new Person(200, "唐僧")); javabean中对象的属性 name=${person1.name }, age=${person1.age }
3.EL表达式取出request中的List<String或基本数据类型> // 设置List List list = new ArrayList(); list.add("刘备"); list.add("关羽"); list.add("张飞"); request.setAttribute("list", list); list中的名字:${personName }
name=${name }, age=${age }

4.EL表达式取出request中的List // 设置List List personList = new ArrayList(); personList.add(new Person(20,"貂蝉")); personList.add(new Person(20,"西施")); personList.add(new Person(20,"王昭君")); request.setAttribute("personList", personList); personList中的名字:${person.name }, 年龄:${person.age }
${str }-->${vs.index }-->${vs.count }
5.EL表达式取出request中的Map的值 Map<Integer, String> userMap = new HashMap<>(); userMap.put(1, "何昭莲"); userMap.put(2, "白红"); userMap.put(3, "王健昌"); userMap.put(4, "苗芙蓉"); userMap.put(5, "罗薇"); request.setAttribute("userMap", userMap); ${map.key }--${map.value }
二、JSTL

JSTL(JavaServer Pages Standard Tag Library,JSP标准标签库) 先将JSTL架包加入项目中 在jsp页面中使用指令 <%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>

最常用的标签就是c:forEach和c:if

c:if 判断条件是写在test里面,只有test成立了,才执行c:if里面的代码 name=${name }, age=${age } c:forEach 装入数据 List strList2 = new ArrayList<>(); for (int i = 0; i < 10; i++) { strList2.add("数据" + i); } request.setAttribute("strList2", strList2); 取出数据

测试c:forEach的更多属性

${str2 } 下标是:${sta.index } -- ${sta.current } --${sta.count } -- ${sta.first } -- ${sta.last }

items:表示要遍历的集合 var: 表示集合里面的每个元素 begin: 表示从哪个下标开始遍历 end: 表示遍历到哪个下标 step: 表示步长,默认为1 varStatus: 和遍历相关的属性 index: 下标 current: 当前元素 count:合计遍历了多少个 从1开始计数,他不等于items的个数 first/last 是否是第一次/最后一次迭代,返回的值是true/false

原文地址:https://www.cnblogs.com/qiuqiutang/p/9812157.html