JSP表达式语言– JSP EL示例教程
今天,我们将研究JSP表达式语言或者JSP EL示例教程。
JSP表达式语言– JSP EL
大多数时候,我们使用JSP进行查看,并且所有业务逻辑都存在于servlet代码或者模型类中。
当我们在Servlet中收到客户端请求时,我们将对其进行处理,然后在request/session/context范围内添加要在JSP代码中检索的属性。
我们还在JSP中使用请求参数,标头,cookie和init参数来创建响应视图。
我们在较早的文章中看到了如何使用scriptlet和JSP表达式通过Java代码检索JSP中的属性和参数,并将其用于视图目的。
但是对于Web设计人员而言,Java代码很难理解,这就是JSP Specs 2.0引入表达式语言(EL)的原因,通过该语言我们可以使用类似HTML的标记轻松获得属性和参数。
表达式语言的语法为${name},我们将了解如何在JSP代码中使用它们。
阅读:的JSP教程
JSP EL隐式对象
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隐式对象,并且只能与JSP EL一起使用。
JSP表达式语言– JSP EL运算符
让我们看一下EL运算符,了解它们的解释方式以及如何使用它们。
EL属性访问运算符或者点(。
)运算符JSP EL点运算符用于获取属性值。
${firstObj.secondObj}在上面的表达式中,firstObj可以是EL隐式对象或者页面,请求,会话或者应用程序范围中的属性。
例如,${requestScope.employee.address}请注意,除了EL的最后一部分,所有对象都应该是Map或者Java Bean,因此在上面的示例中,requestScope是Map,而employee应该是Java Bean或者Map 。
如果未提供范围,则JSP EL将在页面,请求,会话和应用程序范围内进行查找以找到命名属性。JSP EL []运算符或者集合访问运算符[]运算符比点运算符更强大。
我们也可以使用它从List和Array中获取数据。
一些示例; ${myList [1]}和${myList [" 1"]}相同,我们也可以提供List或者Array索引作为String文字。
myMap [expr]} –如果[]中的参数不是String,则将其评估为EL。
${myMap [myList [1]]} – []可以嵌套。
${requestScope [" foo.bar"]} –当属性名称包含点时,我们不能使用点运算符。JSP EL算术运算符提供算术运算符用于EL表达式中的简单计算。
它们是+,-,*,/或者div,%或者mod。JSP EL逻辑运算符它们是&&(和),|| (或者)和! (不)。
JSP EL关系运算符它们是==(eq),!=(ne),<(lt),>(gt),<=(le)和> =(ge)。
JSP表达式语言– JSP EL运算符优先级
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 |
| | |
| ? : |
JSP表达语言– JSP EL保留字
| and | or | not | eq | ne |
|---|---|---|---|---|
| lt | gt | le | ge | true |
| false | null | instanceof | empty | div,mod |
以上是保留字,请不要在JSP中将它们用作标识符。
JSP表达式语言要点
EL表达式始终在大括号内并带有$符号,例如${expr}
我们可以通过将JSP页面指令isELIgnored属性值设置为TRUE来禁用JSP中的EL表达式。
JSP EL可用于获取属性,标头,Cookie,初始化参数等,但我们无法设置这些值。
除了pageContext,JSP EL隐式对象与JSP隐式对象不同,请不要混淆。
提供JSP EL pageContext隐式对象以从请求,响应等获取其他属性,例如,获取HTTP请求方法。
JSP EL是NULL友好的,如果找不到给定的属性或者表达式返回null,则不会引发任何异常。
对于算术运算,EL将null视为0,而对于逻辑运算,EL将null视为false。[]运算符比点运算符更强大,因为我们也可以访问列表和数组数据,可以将其嵌套,并且当[]的参数不是字符串文字时将对其进行求值。
如果您使用的是Tomcat,则使用" org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate()"方法对EL表达式进行求值。
我们可以使用EL函数来从Java类中调用方法,有关更多信息,请参见自定义标签。
JSP EL示例
让我们来看一个简单的应用程序的EL用法。
我们将在不同的范围内设置一些属性,并使用EL来检索它们并在JSP页面中显示。
我们的项目结构如下图所示。
我定义了一些我们将使用的模型类– Person接口,Employee实现的Person和Employee中使用的Address。
package com.theitroad.model;
public interface Person {
public String getName();
public void setName(String nm);
}
package com.theitroad.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.theitroad.model;
public class Employee implements Person {
private String name;
private int id;
private Address address;
public Employee() {
}
@Override
public String getName() {
return this.name;
}
@Override
public 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;
}
@Override
public String toString(){
return "ID="+id+",Name="+name+",Address="+address;
}
}
注意,Employee和Address是具有no-args构造函数和属性的getter-setter方法的Java bean。
我还提供了将在JSP页面中使用的toString()方法的实现。
现在,让我们看一个简单的servlet的代码,该代码将设置一些属性。
package com.theitroad.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.theitroad.model.Address;
import com.theitroad.model.Employee;
import com.theitroad.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 attributes
Person person = new Employee();
person.setName("hyman");
request.setAttribute("person", person);
Employee emp = new Employee();
Address add = new Address();
add.setAddress("San Franceco");
emp.setAddress(add);
emp.setId(1);
emp.setName("hyman 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);
}
}
让我们在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>
使用EL创建视图的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("hyman");names.add("David");
pageContext.setAttribute("names", names);
%>
Simple . EL Example: ${requestScope.person}
<br>
Simple . EL Example without scope: ${person}
<br>
Simple [] Example: ${applicationScope["User.Cookie"]}
<br>
Multiples . EL Example: ${sessionScope.employee.address.address}
<br>
List EL Example: ${names[1]}
<br>
Header information EL Example: ${header["Accept-Encoding"]}
<br>
Cookie EL Example: ${cookie["User.Cookie"].value}
<br>
pageContext EL Example: HTTP Method is ${pageContext.request.method}
<br>
Context param EL Example: ${initParam.AppID}
<br>
Arithmetic Operator EL Example: ${initParam.AppID + 200}
<br>
Relational Operator EL Example: ${initParam.AppID < 200}
<br>
Arithmetic Operator EL Example: ${initParam.AppID + 200}
<br>
</body>
</html>

