【JavaWeb】EL和JSTL

一、EL

 (1)简介

   EL表达式,可以嵌入在jsp页面内部,代替JSP中的脚本语言,目的是为了减少jsp中的JAVA代码,

 (2)利用EL从域中取数据

EL的最主要作用就是从域中取数据

    格式:${EL表达式}     ${里面的get  都会被省略}

    代码:取出request域中一个键的值

            ${requestScope.keyname}

          取出session域中一个键的值

            ${sessionScope.keyname}

注意:

      当取集合的时候

        ${ applicationScope.list[1].name}//       取集合中某一个对象的名字

 使用EL表达式进行全域查找:

        ${ key }

        ${usar.name}  //对象的名字

        ${list[1].name}


    (3)EL的内置对象---因为现在页面中嵌入太多Java代码已经过时,所以主要用EL的取域中数据而不是使用内置对象

    ①4个:pageScope,requestScope,sessionScope,applicationScope

     ---- 获取JSP中域中的数据

    ②2个:param,paramValues - 接收参数.

    相当于request.getParameter()  rrquest.getParameterValues()

    ③2个:header,headerValues  - 获取请求头信息

    相当于request.getHeader(name)

    ④1个:initParam - 获取全局初始化参数

    相当于this.getServletContext().getInitParameter(name)

    ⑤1个:cookie   - WEB开发中cookie

    相当于request.getCookies()---cookie.getName()---cookie.getValue()

    ⑥1个:pageContext- WEB开发中的pageContext.

    pageContext获得其他八大对象

 注意:  ${pageContext.request.contextPath}

相当于

<%=pageContext.getRequest().getContextPath%>  这句代码不能实现

获得WEB应用的名称,来动态获取web应用名称,避免写死代码,比如Web应用名称发生改变



二、JSTL

标准标签库,作用:可以在嵌入Jsp的页面中使用标签的形式完成业务逻辑功能,同时代替jsp中的脚本代码

,配合el使用,常用的是核心库

标签库                    标签的URL                                前缀

core          http://java.sun.com/jsp/jstl/core            c

...(另外四个不怎么用)


导入核心库core代码:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

    (1)JSTL核心库的常用标签

   ①<c:if test=””>标签

        其中test是返回boolean的条件

作用:例如用在判断session域中用户是否登录,若登录显示某些页面信息,若不登陆则显示其他页面信息

   ②<c:forEach>标签  

        使用方式有两种组合形式

	<!-- forEach模拟
		for(int i=0;i<=5;i++){
			syso(i)
		}
	 -->
	 <c:forEach begin="0" end="5" var="i">
	 	${i }<br/>
	 </c:forEach>
	
	<!-- 模拟增强for    productList---List<Product>
		for(Product product : productList){
			syso(product.getPname());
		}
	 -->
	 <!-- items:一个集合或数组   var:代表集合中的某一个元素-->
	 <c:forEach items="${productList }" var="pro">
	 	${pro.pname }
	 </c:forEach>

具体的例子:

①//模拟List<String> strList   遍历一个String的List集合

<h1>取出strList的数据</h1>
	<c:forEach items="${strList }" var="str">
		${str }<br/>
	</c:forEach>

②//遍历List<User>的值   遍历一个User对象的List集合

<h1>取出userList的数据</h1>
	<c:forEach items="${userList}" var="user">
		user的name:${user.name }------user的password:${user.password }<br/>
	</c:forEach>

③//遍历Map<String,String>的值  遍历一个String->String键值对的Map集合

<h1>取出strMap的数据</h1>
	<c:forEach items="${strMap }" var="entry">
		${entry.key }====${entry.value }<br/>
	</c:forEach>

④//遍历Map<String,User>的值    遍历一个String->User对象键值对的Map集合

<h1>取出userMap的数据</h1>
	<c:forEach items="${userMap }" var="entry">
		${entry.key }:${entry.value.name }--${entry.value.password }<br/>
	</c:forEach>


猜你喜欢

转载自blog.csdn.net/toby1123yjh/article/details/79877666