jsp el 表达式

Today we will look into JSP Expression Language or JSP EL Example tutorial.

今天,我们将研究JSP表达式语言或JSP EL示例教程。

JSP表达式语言– JSP EL (JSP Expression Language – JSP EL)

Most of the times we use JSP for view purposes and all the business logic is present in servlet code or model classes. When we receive client request in a servlet, we process it and then add attributes in request/session/context scope to be retrieved in JSP code. We also use request params, headers, cookies and init params in JSP to create response views.

大多数时候,我们使用JSP进行查看,并且所有业务逻辑都存在于servlet代码或模型类中。 当我们在servlet中接收到客户端请求时,我们将对其进行处理,然后在request / session / context范围内添加要在JSP代码中检索的属性。 我们还在JSP中使用请求参数,标头,cookie和init参数来创建响应视图。

We saw in earlier posts, how we can use scriptlets and JSP expressions to retrieve attributes and parameters in JSP with java code and use it for view purpose. But for web designers, java code is hard to understand and that’s why JSP Specs 2.0 introduced Expression Language (EL) through which we can get attributes and parameters easily using HTML like tags.

我们在较早的文章中看到了如何使用scriptletJSP表达式通过Java代码检索JSP中的属性和参数,并将其用于视图目的。 但是对于Web设计人员来说,Java代码很难理解,这就是JSP Specs 2.0引入表达式语言 (EL)的原因,通过它我们可以使用类似HTML的标记轻松获得属性和参数。

Expression language syntax is ${name} and we will see how we can use them in JSP code.

表达式语言的语法为${name} ,我们将了解如何在JSP代码中使用它们。

Read: JSP Tutorial for Beginners

阅读: 初学者的JSP教程

JSP EL隐式对象 (JSP EL Implicit Objects)

JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values. The list is given below.

JSP表达式语言提供了许多隐式对象,我们可以使用它们来获取来自不同作用域和参数值的属性。 列表如下。

JSP EL Implicit Objects Type Description
pageScope Map A map that contains the attributes set with page scope.
requestScope Map Used to get the attribute value with request scope.
sessionScope Map Used to get the attribute value with session scope.
applicationScope Map Used to get the attributes value from application scope.
param Map Used to get the request parameter value, returns a single value
paramValues Map Used to get the request param values in an array, useful when request parameter contain multiple values.
header Map Used to get request header information.
headerValues Map Used to get header values in an array.
cookie Map Used to get the cookie value in the JSP
initParam Map Used to get the context init params, we can’t use it for servlet init params
pageContext pageContext Same as JSP implicit pageContext object, used to get the request, session references etc. example usage is getting request HTTP Method name.
JSP EL隐式对象 类型 描述
pageScope 地图 包含使用页面范围设置的属性的映射。
requestScope 地图 用于获取具有请求范围的属性值。
sessionScope 地图 用于获取具有会话范围的属性值。
应用范围 地图 用于从应用程序范围获取属性值。
参数 地图 用于获取请求参数值,返回单个值
参数值 地图 用于获取数组中的请求参数值,当请求参数包含多个值时很有用。
标头 地图 用于获取请求标头信息。
headerValues 地图 用于获取数组中的标头值。
曲奇饼 地图 用于获取JSP中的cookie值
初始化参数 地图 用于获取上下文初始化参数,我们不能将其用于servlet初始化参数
pageContext pageContext 与JSP隐式pageContext对象相同,用于获取请求,会话引用等。示例用法是获取请求HTTP方法名称。

Note that these implicit objects are different from JSP implicit objects and can be used only with JSP EL.

请注意,这些隐式对象与JSP隐式对象不同,并且只能与JSP EL一起使用。

JSP表达式语言– JSP EL运算符 (JSP Expression Language – JSP EL Operators)

Let’s look at EL Operators and understand how they are interpreted and how to use them.

让我们看一下EL运算符,了解它们的解释方式以及如何使用它们。

  1. EL属性访问运算符或点(。)运算符 (EL Property Access Operator or Dot (.) Operator)

    JSP EL Dot operator is used to get the attribute values.

    ${firstObj.secondObj}

    In the above expression, firstObj can be EL implicit object or an attribute in page, request, session or application scope. For example,

    ${requestScope.employee.address}

    Note that except the last part of the EL, all the objects should be either Map or Java Bean, so in above example, requestScope is a Map and employee should be a Java Bean or Map. If the scope is not provided, the JSP EL looks into page, request, session and application scope to find the named attribute.

    JSP EL Dot运算符用于获取属性值。

    $ {firstObj.secondObj}

    在上面的表达式中,firstObj可以是EL隐式对象,也可以是页面,请求,会话或应用程序范围中的属性。 例如,

    $ {requestScope.employee.address}

    注意,除了EL的最后一部分,所有对象都应该是Map或Java Bean,因此在上面的示例中,requestScope是Map,而employee应该是Java Bean或Map。 如果未提供范围,则JSP EL将在页面,请求,会话和应用程序范围内进行查找以找到命名属性。

  2. JSP EL []运算符或集合访问运算符 (JSP EL [] Operator or Collection Access Operator)

    The [] operator is more powerful than the dot operator. We can use it to get data from List and Array too.

    Some examples;

    ${myList[1]} and ${myList[“1”]} are same, we can provide List or Array index as String literal also.

    ${myMap[expr]} – if the parameter inside [] is not String, it’s evaluated as an EL.

    ${myMap[myList[1]]} – [] can be nested.

    ${requestScope[“foo.bar”]} – we can’t use dot operator when attribute names have dots.

    []运算符比点运算符更强大。 我们也可以使用它从List和Array中获取数据。

    一些例子;

    $ {myList [1]}和$ {myList [“ 1”]}相同,我们也可以提供List或Array索引作为String文字。

    $ {myMap [expr]} –如果[]中的参数不是String,则将其评估为EL。

    $ {myMap [myList [1]]} – []可以嵌套。

    $ {requestScope [“ foo.bar”]} –当属性名称包含点时,不能使用点运算符。

  3. JSP EL算术运算符 (JSP EL Arithmetic Operators)

    Arithmetic operators are provided for simple calculations in EL expressions. They are +, -, *, / or div, % or mod.

    提供了算术运算符,用于EL表达式中的简单计算。 它们是+,-,*,/或div,%或mod。

  4. JSP EL逻辑运算符 (JSP EL Logical Operators)

    They are && (and), || (or) and ! (not).

    它们是&&(和),|| (或)和! (不)。

  5. JSP EL关系运算符 (JSP EL Relational Operators)

    They are == (eq), != (ne), < (lt), > (gt), <= (le) and >= (ge).

    它们是==(eq),!=(ne),<(lt),>(gt),<=(le)和> =(ge)。

JSP表达式语言– JSP EL运算符优先级 (JSP Expression Language – JSP EL Operator Precedence)

JSP EL expressions are evaluated from left to right. JSP EL Operator precedence is listed in below table from highest to lowest.

JSP EL表达式从左到右评估。 下表从高到低列出了JSP EL运算符的优先级。

JSP EL Operator Precedence from Highest to Lowest
[ ] .
() – Used to change the precedence of operators.
– (unary) not ! empty
* / div % mod
+ – (binary)
< > <= >= lt gt le ge
== != eq ne
&& and
|| or
? :
从最高到最低的JSP EL运算符优先级
[]。
()–用于更改运算符的优先级。
–(一元)不行! 空的
* / div%mod
+ –(二进制)
<> <=> = lt ge ge
==!=等式
&&和
|| 要么
? :

JSP表达语言– JSP EL保留字 (JSP Expression Language – JSP EL Reserve Words)

and or not eq ne
lt gt le ge true
false null instanceof empty div,mod
要么 当量 NE
lt gt ge 真正
空值 实例 空的 div,mod

Above are the reserved words, don’t use them as an identifier in JSPs.

上面是保留字,请不要在JSP中将它们用作标识符。

JSP表达式语言要点 (JSP Expression Language Important Points)

  1. EL expressions are always within curly braces prefixed with $ sign, for example ${expr}EL表达式始终在大括号内并带有$符号,例如$ {expr}
  2. We can disable EL expression in JSP by setting JSP page directive isELIgnored attribute value to TRUE.我们可以通过将JSP页面伪指令 isELIgnored属性值设置为TRUE来禁用JSP中的EL表达式。
  3. JSP EL can be used to get attributes, header, cookies, init params etc, but we can’t set the values.JSP EL可用于获取属性,标头,Cookie,初始化参数等,但我们无法设置值。
  4. JSP EL implicit objects are different from JSP implicit objects except pageContext, don’t get confused.除了pageContext,JSP EL隐式对象与JSP隐式对象不同,请不要混淆。
  5. JSP EL pageContext implicit object is provided to get additional properties from request, response etc, for example getting HTTP request method.提供JSP EL pageContext隐式对象可从请求,响应等获取其他属性,例如获取HTTP请求方法。
  6. JSP EL is NULL friendly, if given attribute is not found or expression returns null, it doesn’t throw any exception. For arithmetic operations, EL treats null as 0 and for logical operations, EL treats null as false.JSP EL是NULL友好的,如果找不到给定的属性或表达式返回null,则不会引发任何异常。 对于算术运算,EL将null视为0,而对于逻辑运算,EL将null视为false。
  7. The [] operator is more powerful than dot operator because we can access list and array data too, it can be nested and argument to [] is evaluated when it’s not string literal.[]运算符比点运算符更强大,因为我们也可以访问列表和数组数据,可以将其嵌套,并且当[]的参数不是字符串文字时,将对其进行求值。
  8. If you are using Tomcat, the EL expressions are evaluated using org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate() method.如果使用的是Tomcat,则使用org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate()方法对EL表达式进行求值。
  9. We can use EL functions to call method from a java class, more on this in custom tags post in near future.我们可以使用EL函数来从Java类中调用方法,有关更多信息,请参见自定义标签。

JSP EL示例 (JSP EL Example)

Let’s see EL usage with a simple application. We will set some attributes in different scopes and use EL to retrieve them and show in JSP page. Our project structure will be like below image.

让我们通过一个简单的应用程序查看EL的用法。 我们将在不同的范围内设置一些属性,并使用EL检索它们并在JSP页面中显示。 我们的项目结构如下图所示。

I have defined some model classes that we will use – Person interface, Employee implementing Person and Address used in Employee.

我定义了一些模型类,我们将使用它们-Person接口,Employee实现Person和Employee中使用的Address。

package com.journaldev.model;public interface Person {public String getName();public void setName(String nm);
}
package com.journaldev.model;public class Address {private String address;public Address() {}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String toString(){return "Address="+address;}
}
package com.journaldev.model;public class Employee implements Person {private String name;private int id;private Address address;public Employee() {}@Overridepublic String getName() {return this.name;}@Overridepublic void setName(String nm) {this.name = nm;}public int getId() {return id;}public void setId(int id) {this.id = id;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}@Overridepublic String toString(){return "ID="+id+",Name="+name+",Address="+address;}}

Notice that Employee and Address are java beans with the no-args constructor and getter-setter methods for properties. I have also provided an implementation of toString() method that we will use in JSP page.

注意,Employee和Address是具有no-args构造函数和属性的getter-setter方法的Java bean。 我还提供了将在JSP页面中使用的toString()方法的实现。

Now let’s see the code of a simple servlet that will set some attributes.

现在,让我们看一个设置一些属性的简单servlet的代码。

package com.journaldev.servlet;import java.io.IOException;import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;import com.journaldev.model.Address;
import com.journaldev.model.Employee;
import com.journaldev.model.Person;@WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//Setting some attributesPerson person = new Employee();person.setName("Pankaj");request.setAttribute("person", person);Employee emp = new Employee();Address add = new Address();add.setAddress("India");emp.setAddress(add);emp.setId(1);emp.setName("Pankaj Kumar");HttpSession session = request.getSession();session.setAttribute("employee", emp);response.addCookie(new Cookie("User.Cookie","Tomcat User"));getServletContext().setAttribute("User.Cookie","Tomcat User");RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp");rd.forward(request, response);}}

Let’s define some context init params in the web.xml deployment descriptor.

让我们在web.xml部署描述符中定义一些上下文初始化参数。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"><display-name>JSPELExample</display-name><context-param><param-name>AppID</param-name><param-value>123</param-value></context-param></web-app>

JSP code using EL to create views:

使用EL创建视图的JSP代码:

home.jsp

home.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>JSP EL Example Home</title>
</head>
<body>
<%   List<String> names = new ArrayList<String>();names.add("Pankaj");names.add("David");pageContext.setAttribute("names", names);
%>
<strong>Simple . EL Example:</strong> ${requestScope.person}
<br><br>
<strong>Simple . EL Example without scope:</strong> ${person}
<br><br>
<strong>Simple [] Example:</strong> ${applicationScope["User.Cookie"]}
<br><br>
<strong>Multiples . EL Example:</strong> ${sessionScope.employee.address.address}
<br><br>
<strong>List EL Example:</strong> ${names[1]}
<br><br>
<strong>Header information EL Example:</strong> ${header["Accept-Encoding"]}
<br><br>
<strong>Cookie EL Example:</strong> ${cookie["User.Cookie"].value}
<br><br>
<strong>pageContext EL Example:</strong> HTTP Method is ${pageContext.request.method}
<br><br>
<strong>Context param EL Example:</strong> ${initParam.AppID}
<br><br>
<strong>Arithmetic Operator EL Example:</strong> ${initParam.AppID + 200}
<br><br>
<strong>Relational Operator EL Example:</strong> ${initParam.AppID < 200}
<br><br>
<strong>Arithmetic Operator EL Example:</strong> ${initParam.AppID + 200}
<br><br></body>
</html>

When we send a request for the above servlet, we get output like below image.

当我们发送对上面的servlet的请求时,我们得到如下图所示的输出。

翻译自: https://www.journaldev.com/2064/jsp-expression-language-el-example-tutorial

jsp el 表达式

jsp el 表达式_JSP表达式语言– JSP EL示例教程相关推荐

  1. jsp java el表达式_jsp相关笔记,el表达式、jsp标签库(jstl)

    一.jsp基础部分 1.介绍 概念 JSP(Java Server Page),java服务器端页面,可以定义html标签,又可以定义java代码. 原理 JSP本质上就是一个Servlet 2.JS ...

  2. 不属于jsp构成元素_JSP构成元素-JSP基础

    JSP是Java Server Page的缩写,通常JSP页面使用HTML表示网页上的静态内容,而使用JAVA代码表示动态内容.构成元素包括: 1.静态内容:即一些HTML代码.它与java和jsp的 ...

  3. jsf el表达式_JSP,JSF和EL简介

    jsf el表达式 JavaServer页面,JavaServer Faces和表达语言 在本文中,我将研究JavaServer Pages(JSP)和Expression Language(EL), ...

  4. 对jsp的一个小结(7)EL表达式(不会报错)和JSTL标签库、sp与jdbc总结

    11使用EL显示数据 1EL语法 ①定义变量②变量存入作用域中③访问EL变量.对象属性.数组.运算 <%@page import="java.util.ArrayList"% ...

  5. 在javascript中使用el表达式(jsp中的javascript中支持写el表达式,毋庸置疑,单独的js文件中不支持写el表达式,别钻牛角尖)

    哎,够背的,最后4张图怎么调整都很小,看不清楚,所以大家还是看我这篇文章吧在javascript中使用el表达式(图片清晰版,有图有真相),这篇文章的图片可以正常看清楚,跟我这篇文章是一样的内容! 有 ...

  6. jsf el 表达式_JSF表达式语言– JSF EL

    jsf el 表达式 JSF Expression Language enables users to access the data dynamically from the JavaBeans c ...

  7. java 代码执行el,专属于java的漏洞——EL表达式注入

    前言"FSRC经验分享"系列文章,旨在分享焦点科技信息安全部工作过程中的经验总结,包括但不限于漏洞分析.运营技巧.sdl推行.等保合规.自研工具等等. 欢迎各位安全从业者持续关注~ ...

  8. el表达式 java_JavaWeb(四)EL表达式

    前言 前面详细的说明了什么是JSP和它的一些元素,这篇给大家介绍一下的是EL表达式. 用EL表达式,能更好的使用JSP中的各种内置对象和作用域. 楼主作为大四狗马上要出去面试了,内心很紧张!!! 一. ...

  9. el表达式_EL表达式

    EL 全名为Expression Language EL 语法很简单,它最大的特点就是使用上很方便.接下来介绍EL主要的语法结构: ${sessionScope.user.sex} 所有EL都是以${ ...

最新文章

  1. sshd服务java教程_Windows下安装OpenSSH服务教程
  2. position 再谈
  3. [WebService] xml WebService学习1
  4. 网易技术干货 | 云信Web SDK测试实践
  5. vmware workstation pro 14 虚拟机无法开启、黑屏的解决方案汇总
  6. 数据源管理 | OLAP查询引擎,ClickHouse集群化管理
  7. JSP中的注释操作及JSP中的三种Scriptlet
  8. js-对象深度克隆方法
  9. android runtime异常,在做android下拉刷新时遇到异常java.lang.RuntimeException: Can't create handle...
  10. 面试必掌握的Mysql的11个问题
  11. 浏览器文件服务器计算器设置,【魅蓝 U20使用总结】界面|浏览器|计算器|设置_摘要频道_什么值得买...
  12. 喷墨打印机的使用与维护
  13. 陈丹琦-我是如何学习计算机编程的
  14. OpenCV之图像锐化
  15. Eclipse中更改tomcat版本
  16. 网页设计实验四(DIV+CSS 综合运用 )
  17. Linux RS232驱动实验
  18. 浅谈利用NLG技术来进行游戏自动化(生成随机剧情随机对话)的可行性
  19. !QQ陌生人通过“它”可以和你临时会话!
  20. 【STM32】一次F105 USB OTG驱动填坑记录

热门文章

  1. 3. redis的超时,事务,watch
  2. underscore.js依赖库函数分析一(遍历)
  3. 将Sphinx的日志放置到/dev/shm里需要注意的事情
  4. [摘抄]游戏主循环逻辑
  5. [转载] python函数isdisjoint方法_Python中的isdisjoint()函数
  6. [转载] JAVA中分为基本数据类型及引用数据类型
  7. zabbix4.0LTS安装配置
  8. UE4删除C++Classes下的类
  9. EBS R12.2 创建应用层的启动和关闭脚本
  10. HDU 3394 Railway(点双连通分量)