EL表达式简化了JSP页面的书写,例如以下案例。
Servlet1.java
package zh.servlet.demo; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Servlet1 extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 向request域中存入属性 request.setAttribute("username", "xxdty"); request.setAttribute("password", 666); // 转发 request.getRequestDispatcher("/index.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <p>Java脚本获取域中属性</p> 用户名:<%=request.getAttribute("username") %><br> 密 码:<%=request.getAttribute("password") %><br> 性 别:<%=request.getAttribute("sex") %> <hr> <p>EL表达式获取域中属性</p> 用户名:${requestScope.username }<br> 密 码:${requestScope.password }<br> 性 别:${requestScope.sex } </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>zh.servlet.demo.Servlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/Servlet1</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
访问:http://localhost:8080/JavaWeb1/Servlet1
(1)EL运算符
EL.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <!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> <p>存数据</p> <% request.setAttribute("name", "月亮惹的祸");// 存普通属性 List<String> list = new ArrayList<String>(); list.add("李逍遥"); list.add("赵灵儿"); request.setAttribute("list", list);// 存集合 Object nullObject = null; request.setAttribute("nullObject", nullObject);// 存null对象 request.setAttribute("emptyString", "");// 存空字符串 List<String> emptyList = new ArrayList<String>(); request.setAttribute("emptyList", emptyList);// 存空集合 %> <hr> <p>取数据</p> .运算符:${requestScope.name } 或者 ${requestScope["name"] } <br> []运算符:${requestScope.list[0] },${requestScope.list[1] } <br> 算数运算符: ${1+2 }, ${2*3 },${10/3 }, ${10.0/3 }, ${10%3 }<br> ${1 == 2 },${1 eq 2 }; ${1 != 2 };<br> ${1 < 2 },${1 lt 2 }; ${1 <= 2 },${1 le 2 };<br> ${1 > 2 },${1 gt 2 }; ${1 >= 2 },${1 ge 2 };<br> 逻辑运算符:${true && true },${true and true };<br> ${true || false },${true or false};<br> ${!false },${not false };<br> empty运算符:若果为null、"",或者集合为空,则为true。<br> ${empty requestScope.nullObject };${empty requestScope.emptyString };${empty requestScope.emptyList };<br> 条件运算符:${1 gt 2 ? "1<2" : "1>2" }<br> 【注意】:EL表达式中没有数组下标越界、空指针异常、字符串拼接。 </body> </html>
访问:http://localhost:8080/JavaWeb1/EL.jsp
(2)EL隐式对象
pageContext:可以获得其它隐式对象,包括JSP的隐式对象。
pageScope:表示page域中用于保存属性的Map对象。
requestScope:表示request域中用于保存属性的Map对象。
sessionScope:表示session域中用于保存属性的Map对象。
applicationScope:表示application域中用于保存属性的Map对象。
param:表示保存了所有请求参数的Map集合。
paramvalues:表示保存了所有请求参数的Map集合,但是对于每一个请求参数,都返回一个String[]。
header:表示保存了所有请求头的Map集合。
headervalues:表示保存了所有请求头的Map集合,但是对于每一个请求头,都返回一个String[]。
cookie:表示所有cookie的Map集合,键为cookie的名称,值为对应的cookie对象。
initParam:表示保存了所有Web应用初始化参数的Map对象。
【pageContext】
EL2.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> ${pageContext.request.contextPath}<br> ${pageContext.request.remoteAddr }<br> ${pageContext.request.remoteHost }<br> ${pageContext.request.remotePort }<br> ${pageContext.request.protocol }<br> ${pageContext.request.serverName }<br> ${pageContext.request.serverPort }<br> </body> </html>
【pageScope】、【requestScope】、【sessionScope】、【applicationScope】
EL3.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> <p>存数据</p> <% pageContext.setAttribute("name1", "value1"); request.setAttribute("name2", "value2"); session.setAttribute("name3", "value3"); application.setAttribute("name4", "value4"); %> <p>取数据</p> pageScope:${pageScope.name1 };<br> requestScope:${requestScope.name2 };<br> sessionScope:${sessionScope.name3 };<br> applicationScope: ${applicationScope.name4 }<br> <p>【注意】直接写域中属性名,则按照page、request、session、application域顺序查找。</p> <p>查找不到,则为空</p> ${name1 }<br> ${name2 }<br> ${name3 }<br> ${name4 }<br> ${name5 }<br> </body> </html>
访问:http://localhost:8080/JavaWeb1/EL3.jsp
【param】、【paramValues】
EL4.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> 一键一值:${param.realname }<br> 一键多值:${paramValues.username }<br><!-- 返回String[] --> 一键多值:${paramValues.username[0] }<br><!-- String[]第一个元素 --> 一键多值:${paramValues.username[1] }<br><!-- String[]第二个元素 --> </body> </html>
访问:http://localhost:8080/JavaWeb1/EL4.jsp?realname=xxdty&username=zh1&username=zh2
【header】、【headerValues】
EL5.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> 一键一值:${header["Host"]}<br> 一键一值:${header["User-Agent"]}<br> 一键多值:${headerValues["Accept-Language"]}<br><!-- 返回String[] --> 一键多值:${headerValues["Accept-Language"][0]}<br><!-- String[]第一个元素 --> </body> </html>
访问:http://localhost:8080/JavaWeb1/EL5.jsp
【cookie】
EL61.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> <p>创建并返回:属性名称为username的cookie,其属性值为xxdty</p> <% response.addCookie(new Cookie("username","xxdty")); %> </body> </html>
EL62.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> 获取属性名称为username的cookie对象:${cookie.username }<br> 获取名称为username的cookie对象的属性名称:${cookie.username.name }<br> 获取名称为username的cookie对象的属性值${cookie.username.value }<br> </body> </html>
先访问
再访问
【initParam】
EL7.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> Web应用初始化参数中,名称为myName的属性值为:${initParam.myName }<br> </body> </html>访问EL7.jsp
(3)自定义EL函数
案例:自定义EL函数,防止HTML注入。
form.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>HTML注入</title> </head> <body> <form action="${pageContext.request.contextPath}/ELServlet" method="post"> 用户名:<input type="text" name="username"><br><br> 请留言:<textarea rows="3" cols="20" name="message"></textarea><br> <input type="submit" value="提交"> <input type="reset" value="重置"> </form> </body> </html>
ELServlet.java
package zh.el.demo; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ELServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 解决post提交中文乱码问题 request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String message = request.getParameter("message"); // 存入request域 request.setAttribute("username", username); request.setAttribute("message", message); // 转发 request.getRequestDispatcher("/show.jsp").forward(request, response); } }
show.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> 用户名:${requestScope.username }<br> 留言:${requestScope.message }<br> </body> </html>
访问:http://localhost:8080/JavaWeb1/form.jsp
解决HTML注入问题--------------------------------------------------------------------------------------------
(1)定义执行EL函数的Java类
ELClass.java
package zh.el.demo; public class ELClass { /** * 执行自定义EL函数(必须是静态方法)的Java类 * @param message * @return */ public static String filterHtml(String message){ if(message==null){ return null; } StringBuilder newMessage = new StringBuilder(); char[] charArray = message.toCharArray(); for(int i = 0 ;i<charArray.length;i++){ // 替换< > & "等 switch(charArray[i]){ case '<' : newMessage.append("<"); break; case '>' : newMessage.append(">"); break; case '&' : newMessage.append("&"); break; case '"' : newMessage.append("""); break; default: newMessage.append(charArray[i]); } } return newMessage.toString(); } }
(2)参考以下文件,自定义EL函数
在WEB-INF/mytld中,创建mytld.tld文件,如下:
mytld.tld
<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0"> <description>自定义EL函数</description> <tlib-version>1.0</tlib-version> <short-name>CustomerFunction</short-name> <uri>http://www.zh.cn</uri><!-- 在其它JSP中可以通过此uri来引入该标签库的描述文件 --> <function> <description>防止HTML注入的EL函数</description> <name>filterHtml</name><!-- EL函数名称,可以与函数签名不一样。 --> <function-class>zh.el.demo.ELClass</function-class><!-- 函数所在类的全路径 --> <function-signature>java.lang.String filterHtml( java.lang.String )</function-signature><!-- 函数签名 --> </function> </taglib>
(3)引入自定义的mytld.tld文件
重写show.jsp
show.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="zh" uri="http://www.zh.cn"%><!-- 通过uri引入自定义的mytld.tld文件 --> <!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> 用户名:${requestScope.username }<br> <!-- 调用自定义EL函数 --> 留言:${zh:filterHtml(requestScope.message) }<br> </body> </html>
【测试】
访问:http://localhost:8080/JavaWeb1/form.jsp