02-3 el&jstl


jsp的开发规范:一个标准jsp中不允许出现一行java代码

所以用el和jstl来代替jsp脚本

【EL】

1.EL 表达式概述
 EL(Express Lanuage)表达式可以嵌入在jsp页面内部,减少jsp脚本的编写,
 EL出现的目的是要替代jsp页面中脚本的编写。

2.EL从域中取出数据(EL最重要的作用)
jsp脚本:<%=request.getAttribute(name)%>
EL表达式替代上面的脚本:${requestScope.name}

EL最主要的作用是获得四大域中的数据,格式${EL表达式}
EL获得pageContext域中的值:${pageScope.key};
EL获得request域中的值:${requestScope.key};
EL获得session域中的值:${sessionScope.key};
EL获得application域中的值:${applicationScope.key};
EL从四个域中获得某个值${key};
---同样是依次从pageContext域,request域,session域,application域中    获取属性,在某个域中获取后将不在向后寻找

	<%
		// 模拟Servlet往域中存放数据
		// 简单的String类型
		//pageContext.setAttribute("name", "page-zhangsan");
		//request.setAttribute("name", "request-zhangsan");
		//session.setAttribute("name", "session-zhangsan");
		//application.setAttribute("name", "app-zhangsan");
		
		
		// User类型
		//request.setAttribute("user", new User("zhangsan", "123"));
		
		// List<User>类型
		List<User> list = new ArrayList<User>();
		list.add(new User("zhangsan", "123"));
		list.add(new User("lisi", "234"));
		list.add(new User("wangwu", "345"));
		
		request.setAttribute("uList", list);
		
	%>
	
	<%--原来的方式 --%>
	<%--= request.getAttribute("name") --%>
	
	<%-- el表达式 --%>
	<%-- ${pageScope.name}
	${requestScope.name} 
	${sessionScope.name}
	${applicationScope.name} --%>
	
	<%--分别从4个域中取值 page->request->session->application --%>
	<%-- ${name} --%>
	
	<!-- 从域中取出user的uname属性 -->
	<%--= ((User)request.getAttribute("user")).getUname() --%>
	
	<!-- 用el表达式取出user的uname属性  -->
	<%-- ${user.uname} --%>
	
	<!-- 取出uList中第1个user的upwd属性 -->
	<%--= ((List<User>)request.getAttribute("uList")).get(1).getUpwd() --%>

	EL取出uList中第2个user的uname属性
	${uList[2].uname}

学会取出数据就可以对昨天的显示单一商品代码进行优化

<div class="single">
		<div class="detail">
			<img src="${pageContext.request.contextPath}/images/${product.prodImage}" />
		</div>
		<div class="detail">
			商品名称:${product.prodId}<br /> 商品单价:${product.prodPrice}<br />
			商品库存:${product.prodAmount}<br /> <input type="text" value="1">
			<br /> <input type="button" value="添加到购物车"> <input
				type="button" value="立即购买">
		</div>

	</div>

3.EL的内置对象11个
pageScope,requestScope,sessionScope,applicationScope
 ---- 获取JSP中域中的数据
param,paramValues     - 接收参数.
相当于request.getParameter()  request.getParameterValues()
header,headerValues     - 获取请求头信息
相当于request.getHeader(name)
initParam                - 获取全局初始化参数
相当于this.getServletContext().getInitParameter(name)
cookie                     - WEB开发中cookie
相当于request.getCookies()---cookie.getName()---cookie.getValue()

form1:写一个表单

	<form action="${pageContext.request.contextPath}/el/form2.jsp">
		用户名: <input type="text" name="uname">
		密码: <input type="password" name="upwd">
	
		<input type="submit">
	
	</form>

	弄张图片
	<img src="${pageContext.request.contextPath}/img/prod204.jpg"/>
        //写一个cookie对象,访问本页后,再访问下一个jsp页面获取cookie参数		
        Cookie cookie = new Cookie("name", "zhangsan");
		response.addCookie(cookie);

 form2:通过el内置对象获取参数

	jsp脚本
    <%= request.getParameter("uname") %>
	el内置对象获得
	${ param.uname }
	jsp脚本
	<%= request.getParameter("upwd") %>
    el内置对象获得
	${ param.upwd }
	获取请求头信息
	${header["User-Agent"]}
	获得全局初始化参数
	${initParam.key}
	获得cookie的值
	${cookie.name.value}


pageContext            - WEB开发中的pageContext.
pageContext获得其他八大对象

${pageContext.request.contextPath}

相当于
<%=pageContext.getRequest().getContextPath%>  这句代码不能实现
获得WEB应用的名称:可以把src或者href中的项目名改为用${pageContext.request.contextPath}获取,这样把项目名改了也不会影响正常运行.

4.EL执行表达式
例如:


	<%
		request.setAttribute("name", "");
	%>

	执行表达式 -> 只要有结果, 就可以显示在页面上
	${1+1}

	${empty name}
	
	${user==null?true:false}

【JSTL】

1.JSTL概述
JSTL(JSP Standard Tag Library),JSP标准标签库,可以嵌入在jsp页面中使用标签的形式完成业务逻辑等功能。
jstl出现的目的同el一样也是要代替jsp页面中的脚本代码。
JSTL标准标准标签库有5个子库,但随着发展,目前常使用的是他的核心库(Core)

标签库        标签库的URI                前缀
Core         http://java.sun.com/jsp/jstl/core    c
I18N        http://java.sun.com/jsp/jstl/fmt    fmt
SQL        http://java.sun.com/jsp/jstl/sql    sql
XML        http://java.sun.com/jsp/jstl/xml    x
Functions    http://java.sun.com/jsp/jstl/functions    fn

2.JSTL下载与导入
从Apache的网站下载JSTL的JAR包。进入 http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/

找到jakarta-taglibs-standard-1.1.2\lib子文件夹下的

放到项目名/webContent/WEB-INF/lib下

不用build path,eclipse会自动导包,jar包图标左下角出现类似系统库图标就表示导包完成
使用jsp的taglib指令导入核心标签库
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


3.JSTL核心库的常用标签
1)<c:if test=””>标签
其中test是返回boolean的条件

用另一个取反的if标签来表示else

	<!-- 登录效果
		如果已经登录, 就显示用户名
		如果没有登录, 就显示请登录
	-->
	

	
	判断
	<c:if test="${empty name}">
		请登录
	</c:if>
	<c:if test="${!(empty name)}">
		欢迎你 ${name} 
	</c:if>
	<hr />


2)<c:forEach>标签
使用方式有两种组合形式:

遍历map的实质是遍历map的entry

在<c:forEach>循环体内:取出k-v:${strMap.key}:${strMap.value}

	<%
		// 1. List<String> strList
		List<String> strList = new ArrayList<String>();
		strList.add("a");
		strList.add("b");
		strList.add("c");
		pageContext.setAttribute("strList", strList);
		
		// 2. List<User> uList
		List<User> uList = new ArrayList<User>();
		uList.add(new User("zhangsan", "123"));
		uList.add(new User("lisi", "234"));
		uList.add(new User("wangwu", "345"));
		pageContext.setAttribute("uList", uList);
		
		// 3. Map<String, String> strMap
		Map<String, String> strMap = new HashMap<String, String>();
		strMap.put("one", "一");
		strMap.put("two", "二");
		strMap.put("three", "三");
		pageContext.setAttribute("strMap", strMap);
		
		// 4. Map<String, User> uMap
		Map<String, User> uMap = new HashMap<String, User>();
		uMap.put("zhangsan", new User("zhangsan", "123"));
		uMap.put("lisi", new User("lisi", "123"));
		uMap.put("wangwu", new User("wangwu", "123"));
		pageContext.setAttribute("uMap", uMap);
	%>
	
	
	<hr />
	1. List<String> strList
	<c:forEach items="${strList}" var="str">
	${str}
	</c:forEach>
	<hr />
	2. List<User> uList
	<c:forEach items="${uList}" var="user">
	${user.uname}:${user.upwd}
	</c:forEach>
	<hr />
	3. Map<String, String> strMap
	<c:forEach items="${strMap}" var="strMap">
	${strMap}
	</c:forEach>
	<hr />
	4. Map<String, User> uMap
    遍历map的实质是遍历map的entry
    <%-- 对象导航 --%>
	<c:forEach items="${uMap}" var="strMap">
	${strMap.key}:${strMap.value.uname}:${strMap.value.upwd}
	</c:forEach>


学了<c:forEach>标签,那么就可以对昨天显示商品.jsp里的循环语句进行优化,把jsp脚本全部去掉

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page import="com.wowowo.bean.Product" %>
<%@ page import="com.wowowo.bean.PageBean" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ 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>Insert title here</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link
	href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
	rel="stylesheet">
<script
	src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script
	src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<style type="text/css">
.prod {
	border: 1px solid black;
	width: 230px;
}

.prod_price {
	float: right;
}
</style>
</head>
<body>
	<h1 class="text-center">欢迎访问服装商城</h1>
	<div class="container">

	<c:forEach items="${pageBean.data}" var="product">
		<div class="prod col-md-3">
			<div>
				<a href="${pageContext.request.contextPath}/single?uid=${product.prodId}"><img
					src="${pageContext.request.contextPath}/images/${product.prodImage}" /></a>
			</div>
			<div>
				${product.prodName}
				<span class="prod_price">价格:
					${product.prodPrice}
				</span>
			</div>
		</div>
		</c:forEach>
		
	</div>
	<div style="text-align: center;">
		<a href="goods?pageNum=1&pageSize=5" class="btn btn-danger">首页</a>		
		<a		
			href="goods?pageNum=${pageBean.pageNum<=1?1:pageBean.pageNum-1}&pageSize=5"
			class="btn btn-danger">上一页</a>
		<a href="goods?pageNum=${pageBean.pageNum>=pageBean.pageMaxSize?pageBean.pageNum:pageBean.pageNum+1}&pageSize=5"
			class="btn btn-danger">下一页</a>
		<a href="goods?pageNum=${pageBean.pageMaxSize}&pageSize=5"
			class="btn btn-danger">末页</a>
	</div>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_36194262/article/details/83379691