Java Web程序设计——EL表达式和JSTL

Java Web程序设计——EL表达式和JSTL

ps:这章有点多。。。
思维导图:
在这里插入图片描述

初识JavaBean

什么是JavaBean
  • 是java开发中常用的组件,其实就是一个java类,作用就是用来封装数据
  • 书写JavaBean需要满足五个规范:1.要被public修饰
    2.要提供公共的无参数的构造方法
    3.要提供私有的属性
    4.要给私有的属性提供公共的set或者get方法
    5.要实现Serializable接口

例:

package chapter;

public class Book {
	private double price;

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}
	

}
访问JavaBean的属性
  • 类的成员变量和属性的关系:在普通的java类里面,成员变量可以说成就是属性。在JavaBean里面,成员变量和属性就有了区别。
  • 在JavaBean中:比如:private String id;id就是成员变量。get或者set后面的字段名称(字段名称的首字母小写)就是属性。

例:

package chapter07;

public class Student {
	//以下就是JavaBean的四个成员变量
	private String sid;  //目的就是为了接受外界传递过来的值
	private String name;
	private String age;
	private boolean married;
	public Student() {
		super();
	}
	//属性由get或者set方法后面的字段首字母小写就是属性,属性就是id
	public String getSid() {
		return sid;
	}
	public void setSid(String sid) {//写方法,给student写一个id
		this.sid = sid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
		
}

上面的student属性就是id和name,成员变量就是sid和name

BeanUtils工具
  • BeanUtils工具是由apache软件基金会提供的一套封装数据到BeanUtils的工具类,使用简单方便。
  • BeanUtils是第三方的工具(插件),所以需要导入jar包
  • BeanUtils类常用的方法:
    在这里插入图片描述
    注:map对象的key,也就是JavaBean属性名称,必须和JavaBean的属性名一致,才能给JavaBean设置属性值

例:
Person类:

package chapter07;

public class Person {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Person() {
		super();
	}
	
}

BeanUtilsDemo类:

package chapter07;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

public class BeanUtilsDemo {
	public static void main(String[] args) throws Exception {
		Person p = new Person();
		//1.设置属性
		BeanUtils.setProperty(p, "name", "zhangsan");
		BeanUtils.setProperty(p, "age", 21);
		//2.获取属性的值
		String name1 = BeanUtils.getProperty(p, "name");
		int age1 = Integer.parseInt(BeanUtils.getProperty(p, "age"));
		System.out.println(name1);
		System.out.println(age1);
		//使用populate设置属性值
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("name","lisi");
		map.put("age", 21);
		BeanUtils.populate(p, map);
		String name2 = BeanUtils.getProperty(p, "name");
		int age2 = Integer.parseInt(BeanUtils.getProperty(p, "age"));
		System.out.println(name2);
		System.out.println(age2);
	}
}

运行
在这里插入图片描述

EL表达式

初识EL
  • EL在开发中,通常用来获取域对象中保存的值。
  • 基本语法:
${域对象名称}
  • 这个域对象的名称可以理解为就是EL中的变量,那这个变量就不需要定义了,可以直接使用

例:

MyServlet

package chapter07;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyServlet
 */
public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.使用request域对象存值
		request.setAttribute("username", "CSDN");
		request.setAttribute("password", "123456");
		// 2.把当前的请求转发到myjsp.jsp
		RequestDispatcher dis = request.getRequestDispatcher("myjsp.jsp");
		dis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

myjsp.jsp

<%@ 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>
</head>
<body>
	<!-- 第一种方式获取值 -->
	<%= request.getAttribute("username") %><br/>
	<%= request.getAttribute("password") %><br/>
	<hr/>
	<!-- 第二种方式获取值 -->
	${ username }<br/>
	${ password }
</body>
</html>

浏览器打开:

在这里插入图片描述
注:如果域对象名称写错了,使用EL表达式取值,获取的值返回空字符串。而使用java方式获取,返回的值是null时,会报空指针异常。

EL中的标识符
  • 在EL书写过程中,会使用一些符号标记一些名称,如变量名,自定义函数名等。这些符号被称为标识符。
  • 在定义标识符时还需要遵循以下规范:
  1. 不能以数字开头
  2. 不能是EL中的关键字,如and,or等
  3. 不能是EL隐式对象,如pageContext
  4. 不能包含单引号、双引号、减号和正斜线等特殊字符

例:

username
username123
user_name
_userName
EL中的关键字

在这里插入图片描述

EL中的常量
  • 布尔常量:true或false
  • 数字常量:整型、浮点常量,使用方式和java差不多
  • 字符串常量:比如:${“el的字符串常量”}
  • Null常量:表示变量 引用的对象为空
EL中的运算符
  • 点运算符:获取域对象中属性的值,比如:
${person.name}
  • 方括号运算符:在域对象里,有点属性包含特殊字符,所以用方括号的方式来获取值,比如:
${user["My-Name"]}
  • 算术运算符:+ - * %
  • 比较运算符:> < >= <= == != 所有执行的结果都是布尔类型
  • 逻辑运算符:&& || !
  • empty运算符:用于判断某个对象是否为null或者" "。结果为布尔类型,比如;
${empty var}
  • 三目运算符:类似于java语言中的if-else语句,格式如下:
${A?B:C}
  • “( )”运算符:圆括号用于改变其他运算符的优先级,例如${a*b+c}正常情况下会先计算a*b的积,修改为${a*(b+c)}则先计算b+c的和,在计算的结果与a相乘
EL隐式对象
  • EL中11个隐式对象:
    在这里插入图片描述
  1. pageContext对象:
获取项目的路径: ${ pageContext.request.contextPath }<br/>
获取请求的URL: ${ pageContext.request.requestURI }
  1. web域相关的对象:域作用范围从小到大:pageContext–>request–>session–>application(servletContext)
    如果域对象的名称相同,获取的是域作用范围最小的值和pageContext对象的findAttribute方法的效果是一样的

例:

<%@ 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>
</head>
<body>
	<% 	pageContext.setAttribute("page", "PAGE");
		request.setAttribute("request", "REQUEST");
		session.setAttribute("session", "SESSION");
		application.setAttribute("appl", "APPLICATION");
	%>
	${ pageScope.page } =======${ page }<br/>
	${ requestScope.request } =======${ request }<br/>
	${ sessionScope.session } =======${ session }<br/>
	${ applicationScope.appl } ======${ appl }
	
</body>
</html>
  1. param和paramValues对象:获取表单提交的数据

例:

<%@ 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>
</head>
<body>
	<form action="${pageContext.request.contextPath }/param.jsp"method="get">
		num1:<input type="text" name="num1"/><br/>
		num2:<input type="text" name="num"/><br/>
		num3:<input type="text" name="num"/><br/>
		<input type="submit" value="提交"/>&nbsp;&nbsp;<input type="reset" value="重置"/>
		<hr/>
		num1:${param.num1 }<br/>
		num2:${paramValues.num[0] }<br/>
		num3:${paramValues.num[1] }
	</form>
	
</body>
</html>

在这里插入图片描述

在这里插入图片描述

  1. Cookie对象:获取cookie的名称和值

例:

<%@ 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>
</head>
<body>
	<% response.addCookie(new Cookie("userName","DTRblank")); %>
	获取cookie对象:${cookie.userName }<br/>
	获取cookie名称:${cookie.userName.name }<br/>
	获取cookie值:${cookie.userName.value }<br/>
</body>
</html>

在这里插入图片描述

JSTL

什么是JSTL
  • JSTL:JavaServer Pages Standard Tag Libary,java服务器端页面的标准标签库。其实就是在jsp页面上使用的标签库。
  • JSTL标签库有五个组成,通常使用核心标签库。
  • JSTL包含的标签库:
    在这里插入图片描述
JSTL的安装和测试

步骤:1.在JSP页面使用taglib指令引入标签库,下载网址:http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/
2.导入JSTL相关的jar包,lib目录下的两个导入eclipse中
在这里插入图片描述
在这里插入图片描述
3.测试一下

<%@ 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>Insert title here</title>
</head>
<body>
	<c:out value="hello jstl!"></c:out>
</body>
</html>

在这里插入图片描述

JSTL中Core标签库
<c:out>标签
  • <c:out>标签:向网页输出内容
  • 语法1:没有标签体的情况:
<c:out value="value"[default="defaultValue"]>
[escapeXml="{true|false"}/]
</c:out>
  1. value属性:用于指定输出的文本内容
  2. default属性:指定当value属性为null时所输出的默认值

例:

<%@ 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>Insert title here</title>
</head>
<body>
	<!-- 第一种 -->
	<c:out value="${param.username}" default="unknown" escapeXml="true" ></c:out><br/>
	<!-- 第二种 -->
	<c:out value="${param.username}" escapeXml="true">unknown</c:out>
</body>
</html>

在这里插入图片描述
在这里插入图片描述

  • 语法2:有标签体的情况,在标签体中指定输出的默认值
<c:out value="value"[escapeXml="{true|false}"]>
defaultValue
</c:out>
  1. escapeXml属性(默认值为true):如果为true,就会把html标记当成普通的字符串输出,如果为false就会正常解析html标记,正常输出。

例:

<%@ 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>Insert title here</title>
</head>
<body>
	<!-- 第二种 -->
	<c:out value="${param.username}" escapeXml="false">
		<a href="https://www.csdn.net/">点击这里,跳转到CSDN官网</a>
	
	</c:out>
</body>
</html>

在这里插入图片描述

<c:if>标签
  • <c:if>标签:进行条件判断,和java类中的if很相似
  • 语法1:没有标签体情况
<c:if test="testCondition" var="resulst" 
[scope="{page|request|session|application}"]/>
</c:if>
  • 语法2:有标签体情况,在标签体中指定要输出的内容
<c:if test="testCondition" var="resulst" 
[scope="{page|request|session|application}"]>body content
</c:if>
  1. test属性:如果返回值为true,就输出标签体内容,否则就不输出
  2. var属性:用于指定逻辑表达式中变量的名字
  3. scope属性:用于指定var变量的作用范围,默认值为page
  4. 在开发中经常使用第二种

例:

<%@ 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>Insert title here</title>
</head>
<body>
	<%-- request.setAttribute("key",1); --%>
	<c:set var="key" value="1" scope="request" property="key"></c:set>
	<c:if test="${key==1}">
		hello c:if标签
	</c:if>
</body>
</html>

在这里插入图片描述

<c:choose>标签
  • <c:choose>标签:进行条件判断,和java类中的if,else if()很相似
  • 语法格式:
<c:choose>
	<c:when test="条件表达式">标签体内容</c:when>
	<c:when test="条件表达式">标签体内容</c:when>
	......
	<c:otherwise>标签体内容</c:otherwise>
</c: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>Insert title here</title>
</head>
<body>
	<c:choose>
		<c:when test="${empty param.username}">
			未知用户
		</c:when>
		<c:when test="${param.username=='blank'}">
			${ param.username } is author
		</c:when>
		<c:otherwise>
			${ param.username } is person
		</c:otherwise>
	</c:choose>
</body>
</html>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

<c:foreach>标签
  • <c:foreach>标签:遍历域对象中的数组和集合,和java类中的for循环很相似
  • 语法1:普通for
<c:forEach var="元素" items="数组或者集合中的值" begin="开始的下标" end="结束的下标" step="遍历的增量">
</c:forEach>

例:

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ 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>Insert title here</title>
</head>
<body>
	colorsList集合(指定迭代范围和步长)<br/>
	<%
		List colorsList = new ArrayList();
		colorsList.add("red");
		colorsList.add("yellow");
		colorsList.add("blue");
		colorsList.add("green");
		colorsList.add("black");
		colorsList.add("gray");
		request.setAttribute("list", colorsList);
	%>
	<c:forEach var="aa" items="${list}" begin="1" end="4" step="2">
		${aa}
	</c:forEach>
</body>
</html>

在这里插入图片描述

  • 语法2:增强for
<c:forEach var="元素" items="数组或者集合中的值">
</c:forEach>

例:

<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ 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>Insert title here</title>
</head>
<body>
	<% 
		String[] fruits = {"apple","peach","orange","grape"};
		request.setAttribute("ff", fruits);
	%>
	String数组中的元素:
	<br/>
	<c:forEach var="yy" items="${ ff }">
		${yy }<br/>
	</c:forEach>
	<% 
		Map userMap = new HashMap();
		userMap.put("Ann", "123");
		userMap.put("Mike", "123");
		userMap.put("Tom", "123");
		request.setAttribute("map", userMap);
	%>
	<hr/>
	HashMap集合中的元素:
	<br/>
	<c:forEach var="m" items="${map }">
		key:${m.key }------value:${m.value }<br/>
	</c:forEach>
</body>
</html>

在这里插入图片描述

<c:param>标签和<c:url>标签
  • <c:param>标签和<c:url>标签:设置路径和传递参数
  • 基本语法:
<c:url var="变量名称" url="路径值">
	<c:param name="属性名称" value="属性值"></c:param>
</c:url>

例:

<%@ 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>Insert title here</title>
</head>
<body>
	使用绝对路径:<br/>
	<c:url var="absolateURL" value="http://localhost:8080/chapter07/login.html">
		<c:param name="username" value="blank"></c:param>
		<c:param name="country" value="China"></c:param>
	</c:url>
	<a href="${absolateURL}">绝对路径</a>
	<hr/>
	使用相对路径:<br/>
	<c:url var="risistURL" value="login.html?username=blank&country=China"></c:url>
	<a href="${risistURL }">相对路径</a>
</body>
</html>

注:开发的访问路径:1.绝对路径:第一种:http://localhost:8080/chapter07/login.html
第二种:/chapter07/login.html
2.相对路径:直接写访问资源路径:比如:ligin.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaWeb 中,使用 EL 达式JSTL 可以实现在 JSP 页面中进行动态数据处理和展示。下面我来分别介绍这两种技术的实现方法。 1. EL 达式的实现 EL 达式是一种用于在 JSP 页面中访问 JavaBean 中属性的语言。在 JSP 页面中,我们可以通过 ${} 语法来使用 EL 达式。例如,我们可以通过 ${user.name} 来获取 JavaBean 中的 name 属性的值。 要在 JavaWeb 中使用 EL 达式,我们需要完成以下步骤: 1) 在 JSP 页面中引入 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>,指定页面编码为 UTF-8。 2) 在 JSP 页面中引入 JSTL 标签库 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>。 3) 在 JavaBean 中定义属性,并提供 getter 和 setter 方法。 4) 在 JSP 页面中使用 EL 达式来访问 JavaBean 的属性值。例如:${user.name}。 2. JSTL 的实现 JSTL 是一组 JSP 自定义标签,用于在 JSP 页面中进行动态数据处理和展示。JSTL 提供了一些常用的标签库,例如 core、fmt、sql、xml 和 functions 等。 要在 JavaWeb 中使用 JSTL,我们需要完成以下步骤: 1) 在 JSP 页面中引入 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>,指定页面编码为 UTF-8。 2) 在 JSP 页面中引入 JSTL 标签库 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>。 3) 在 JSP 页面中使用 JSTL 标签库提供的标签来进行动态数据处理和展示。例如,使用 <c:forEach> 标签来遍历一个集合: ``` <c:forEach var="item" items="${list}"> ${item} </c:forEach> ``` 这样就可以在 JSP 页面中使用 EL 达式JSTL 来进行动态数据处理和展示了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值