1 EL表达式的基本概述
EL(Express Lanuage)表达式可以嵌入在jsp页面内部,减少jsp脚本的编写,EL 出现的目的是要替代jsp页面中输出脚本<%= 数据 %>的编写。
2 EL表达式的格式和作用
EL表达式的格式:
${EL表达式内容}
EL表达式的作用:
- 从域对象中查找指定的数据。
- EL内置对象的使用
- 执行运算符
3 EL表达式的基本使用(从域中取出数据)
- EL从四个域中获得某个值:
${key}
- 作用范围从小到大是依次从pageContext域,request域,session域,application域中 获取属性,在某个域中获取后将不在向后寻找
- 其中,若只想获得pageContext域中的值:
${pageScope.key}
- 其中,若只想获得request域中的值:
${requestScope.key}
- 其中,若只想获得session域中的值:
${sessionScope.key}
- 其中,若只想获得application域中的值:
${applicatioScope.key}
3.1 通过EL表达式,获得普通数据
- 格式:
${key}
- 这样 EL从四个域中,按从小到大的顺序查找key,找到则输出,不再继续寻找。具体看下面例子。
代码演示:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>获取域容器中的数据</title>
</head>
<body>
<%
// 1 将数据保存到域容器中
pageContext.setAttribute("city", "北京1"); // page
pageContext.setAttribute("city", "北京2", PageContext.REQUEST_SCOPE); // request
pageContext.setAttribute("city", "北京3", PageContext.SESSION_SCOPE); // session
pageContext.setAttribute("city", "北京4", PageContext.APPLICATION_SCOPE); // servletContext
// 2 删除指定域数据
/*
pageContext.removeAttribute("city", PageContext.PAGE_SCOPE); // page
pageContext.removeAttribute("city", PageContext.REQUEST_SCOPE); // request
pageContext.removeAttribute("city", PageContext.SESSION_SCOPE); // session
pageContext.removeAttribute("city", PageContext.APPLICATION_SCOPE); // servletContext
*/
pageContext.removeAttribute("city"); // 删除所有域中的数据
%>
<h1>java</h1>
<h3>获取数据</h3>
<%
out.print(pageContext.getAttribute("city")!=null?pageContext.getAttribute("city"):""); // page
out.print(pageContext.getAttribute("city", PageContext.REQUEST_SCOPE)); // request
out.print(pageContext.getAttribute("city", PageContext.SESSION_SCOPE)); // session
out.print(pageContext.getAttribute("city", PageContext.APPLICATION_SCOPE)); // servletContext
%>
<h3>智能获取数据</h3>
<%
/*
pageContext.findAttribute(key) 根据key从四个域容器中依次获取数据, 如果获取到了,取值结束; 如果都没有获取到, 返回null
*/
out.print(pageContext.findAttribute("city"));
%>
<h1>EL</h1>
<h3>获取数据</h3>
${pageScope.city}
${requestScope.city}
${sessionScope.city}
${applicationScope.city}
<h3>智能获取数据</h3> <%--最常用的就是这个--%>
${city}
</body>
</html>
3.2 EL获得javaBean对象的值
格式:
${对象.成员变量}
假设User是一个javaBean对象:
public class User {
private String username;
private String password;
private String nickname;
//省略构造方法、get、set方法
}
代码演示:
<%@ page import="cn.itcast.pojo.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
// EL获得javaBean对象的值
User user = new User();
user.setUsername("zhangsan");
user.setPassword("abc");
// 放置在request域中,因为EL表达式只能获取到域中数据
request.setAttribute("user", user);
%>
<%--最一般java语句,一般不采用--%>
<h1>java</h1>
username = <%=((User)pageContext.findAttribute("user")).getUsername()%> <br/>
password = <%=((User)pageContext.findAttribute("user")).getPassword()%> <br/>
nickname = <%=((User)pageContext.findAttribute("user")).getNickname()%>
<hr/>
<%--EL语句获取,最常用,也最简单--%>
<h1>EL</h1>
username === ${user.username} <br/>
password === ${user.password} <br/>
nickname === ${user.nickname} <br/>
</body>
</html>
3.3 EL获得 List<String>
的值
List<String>
格式:
代码演示
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
EL表达式作用一(从域中取出数据): EL获得 List<String> 的值
格式: ${ List集合对象[索引] }
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--1.创建 List<String>集合, 存到Request域中 --%>
<%
List<String> list = new ArrayList<String>();
list.add("热巴");
list.add("娜扎");
request.setAttribute("list",list);
%>
<%--2.通过EL表达式, 获取List<String>集合中的数据--%>
<%--jsp方式获取,不推荐使用--%>
<%
List<String> names = (List<String>) request.getAttribute("list");
out.print( names.get(0) +" === "+ names.get(1) );
%>
<%--EL方式获取--%>
${list[0]} == ${list[1]}
</body>
</html>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eEgMw0t8-1606008306083)(day08_jsp&filter&listener.assets/1568520799607.png)]
3.4 EL获得 List<User>
的值
List<User>
格式:
${List集合对象[索引].成员变量}
代码演示
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.itheima.pojo.User" %><%--
EL表达式作用一(从域中取出数据): EL获得 List<User> 的值
格式: ${ List集合对象[索引].成员变量 }
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--1.创建 List<User>集合, 存到Request域中 --%>
<%
List<User> list = new ArrayList<User>();
list.add(new User("热巴","123456"));
list.add(new User("娜扎","abcdef"));
request.setAttribute("list",list);
%>
<%--2.通过EL表达式, 获取 List<User>集合中的数据--%>
<%--jsp方式获取--%>
<%
List<User> users = (List<User>) request.getAttribute("list");
out.print( users.get(0).getUsername() +"=="+ users.get(0).getPassword() );
out.print( users.get(1).getUsername() +"=="+ users.get(1).getPassword() );
%>
<br/>
<%--EL方式获取--%>
${list[0].username} == ${list[0].password}
${list[1].username} == ${list[1].password}
</body>
</html>
输出:

3.5 EL获得Map<String,User>的值
格式:
${Map集合对象.key.成员变量}
或
${Map集合对象['key'].成员变量}
代码演示
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.itheima.pojo.User" %>
<%@ page import="java.util.Map" %><%--
EL表达式作用一(从域中取出数据): EL获得 Map<String, User> 的值
格式:
${Map集合对象.key.成员变量 }
或
${Map集合对象['key'].成员变量}
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--1.创建 Map<String, User>集合, 存到Request域中 --%>
<%
Map<String, User> userMap = new HashMap<String, User>();
userMap.put("user1", new User("热巴","123456"));
userMap.put("user2", new User("娜扎","abcdef"));
request.setAttribute("userMap",userMap);
%>
<%--2.通过EL表达式, 获取 Map<String, User>集合中的数据--%>
<%--jsp方式获取,不推荐--%>
<%
Map<String, User> map = (Map<String, User>) request.getAttribute("userMap");
out.print( map.get("user1").getUsername() +"=="+ map.get("user1").getPassword());
out.print( map.get("user2").getUsername() +"=="+ map.get("user2").getPassword());
%>
<br/>
<%--EL方式获取,一般采用第一种方式--%>
${userMap.user1.username} == ${userMap.user1.password}
${userMap.user2.username} == ${userMap.user2.password}
<br/>
${userMap['user1'].username} == ${userMap['user1'].password}
${userMap['user2'].username} == ${userMap['user2'].password}
</body>
</html>
4 EL的内置对象 pageContext
-
: WEB开发中的页面的上下文对象.pageContext
作用:可以用来获取JSP中四个域中的数据(pageScope, requestScope, sessionScope, applicationScope)
- 例如,在Servlet中,想获得web应用的名称:
request.getContextPath();
- 那么,在jsp页面上,想获得web应用的名称:
${pageContext.request.contextPath}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>获取WEB应用项目名称</title>
</head>
<body>
<h3>获取WEB应用项目名称</h3>
<%--JSP方式获取--%>
<%= request.getContextPath()%>
<%--EL方式获取--%>
${pageContext.request.contextPath}
</body>
</html>
5 EL执行运算符(了解)
- 算数运算符 + , - , * , / , %
- 逻辑运算符 && , || , !
- 比较运算符 > , < , >= , <= , == , !=
- Null运算符 empty
- 三元运算符
代码演示:
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>EL执行运算符</title>
</head>
<body>
${3+4} <br>
${3-4} <br>
${true&&true} <br>
${false&& true} <br>
${3>4} <br>
${3<4 || 5>4} <br>
<%--向域中存数据, 用于演示 empty--%>
<%
String str = null;
request.setAttribute("str", str);
request.setAttribute("array", new String[1] );
request.setAttribute("list", new ArrayList<String>());
%>
${empty str} <br>
${empty array} <br>
${empty list} <br>
${str == null?"数据为空":str} <br>
</body>
</html>
输出:
6 案例 记录上一次登录所使用的用户名
-
问题描述
在登录界面,如果输入用户名和密码后,勾选了记住用户名,点击登录后,下次打开登录页面用户名会自动填入。
-
步骤分析:
① 获取提交的用户名密码
② 获取是否 “记住用户名”
③ 判断用户名和密码是否和数据库中的匹配:若匹配,重定向到首页;若不匹配,转发回登录页面,提示用户名或者密码错误; 同时,只要勾选了记住用户名,就获取cookie中的username值.显示在页面上
-
实现方法:
① 登录表单的提交地址是Servlet
② 在Servlet中,获取到用户名和密码后和数据库中数据对比,成功或失败跳转到相应页面
③ 判断提取的表单中是否勾选了记住用户名按钮,若是,将用户名存放到Cookie中,在登录页面获取并显示。
-
将用户名放到Cookie中的合理性:
如果放置在服务器中,当服务器升级或维修时就无法获取到数据。
- 先看登录界面
代码:login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<%--注意这里,获取提交路径的方式--%>
<form action="${pageContext.request.contextPath}/login" method="post">
<table>
<tr>
<td>用户名</td>
<%--注意这里-获取输入值的方式-%>
<td><input type="text" name="username" value="${cookie.user.value}"/></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name="rem" value="remUsername"> 记住用户名</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
- 下面看一下处理的Servlet代码
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 处理记住用户名的操作
* 1. 用户名和密码的验证
* 2.记录用户名
*/
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 2.判断
if (username.equals("tom") && password.equals("1234")){
//登录成功
response.getWriter().write("login success");
}else {
// 登录失败
request.setAttribute("message","登录失败!用户名或密码错误,请重新输入");
// 转发到登录页面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
// 获取表单中是否勾选了记住用户名,如果勾选,将用户名存放到cookie中
String rem = request.getParameter("rem");
if (rem != null){
// 勾选了记住用户名
Cookie cookie = new Cookie("user",username);
cookie.setMaxAge(60*10*24*10); //记住10天
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}