使用EL表达式获取数据和使用JSTL标签库迭代容器

               

为了避免在JSP页面中出现Java代码和显示Servlet处理完成带过来的数据并且显示,使用EL表达式会非常容易而且简介,但是对于存放在容器中的数据,EL表达式不能单独完成迭代输出,所以必须使用JSTL标签库配合使用,这个是JavaEE附带的一个非常强大的标签库,估计在以后还会用到。

首先是EL表达式的几个不同情况的用法

<%@page import="com.bird.domain.Db"%><%@page import="com.bird.domain.Address"%><%@page import="com.bird.domain.Person"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>EL表达式的应用</title>      </head>    <body>  <%   String date = "abcd";   request.setAttribute("date",date);   %>      ${date} <!-- 会被翻译成pageContext.findAttribute("date")分别从page,request,session,servletcontext查找   如果寻找不到,则返回“”空字符串    -->            <%    Person p = new Person();    p.setName("小白");    request.setAttribute("person",p);     %>          ${person.name}               <%     Person p1= new Person();     Address a  = new Address();     a.setCity("北京");     p1.setAddress(a);     request.setAttribute("p1",p1);      %>           ${p1.address.city}                         <%      List<Db> list = new ArrayList<Db>();      list.add(new Db("aaaaaa"));      list.add(new Db("bbbbbb"));      list.add(new Db("cccccc"));            request.setAttribute("list",list);      %>            ${list[1].name }                        <%      Map map = new HashMap();      map.put("aa",new Db("aaaa"));      map.put("bb",new Db("bbbb"));      map.put("cc",new Db("cccc"));      map.put("dd",new Db("dddd"));            request.setAttribute("map",map);             %>              ${map.aa.name }<%--用表达式一般用点号,点号不行用[] --%>                     ${pageContext.request.contextPath }  </body></html>

下面的是使用El表达式和JSTL标签库配合使用来完成容器的迭代

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%><%@page import="com.bird.domain.Db"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"  %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>使用JSTL+EL表达式完成集合迭代</title>      </head>    <body>   <%      List<Db> list = new ArrayList<Db>();      list.add(new Db("aaaaaa"));      list.add(new Db("bbbbbb"));      list.add(new Db("cccccc"));            request.setAttribute("list",list);      %>            <c:forEach var="person" items="${list }">      ${person.name }      </c:forEach>            <br/>             <%      Map map = new HashMap();      map.put("aa",new Db("aaaa"));      map.put("bb",new Db("bbbb"));      map.put("cc",new Db("cccc"));      map.put("dd",new Db("dddd"));            request.setAttribute("map",map);             %>              <c:forEach var="entry" items="${map }">       ${entry.key } : ${entry.value.name }       </c:forEach>  </body></html>


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43679366/article/details/87866612