1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > jsp el 表达式_JSP表达式语言– JSP EL示例教程

jsp el 表达式_JSP表达式语言– JSP EL示例教程

时间:2023-10-24 10:21:28

相关推荐

jsp el 表达式_JSP表达式语言– JSP EL示例教程

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 usescriptletsandJSP expressionsto 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 introducedExpression 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表达式语言提供了许多隐式对象,我们可以使用它们来获取来自不同作用域和参数值的属性。 列表如下。

Note that these implicit objects are different fromJSP implicit objectsand 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运算符,了解它们的解释方式以及如何使用它们。

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将在页面,请求,会话和应用程序范围内进行查找以找到命名属性。

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”]} –当属性名称包含点时,不能使用点运算符。

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。

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

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

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

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表达语言– JSP EL保留字 (JSP Expression Language – JSP EL Reserve Words)

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

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

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

EL expressions are always within curly braces prefixed with $ sign, for example ${expr}EL表达式始终在大括号内并带有$符号,例如$ {expr} We can disable EL expression in JSP by settingJSP page directiveisELIgnored attribute value to TRUE.我们可以通过将JSP页面伪指令isELIgnored属性值设置为TRUE来禁用JSP中的EL表达式。 JSP EL can be used to get attributes, header, cookies, init params etc, but we can’t set the values.JSP EL可用于获取属性,标头,Cookie,初始化参数等,但我们无法设置值。 JSP EL implicit objects are different from JSP implicit objects except pageContext, don’t get confused.除了pageContext,JSP EL隐式对象与JSP隐式对象不同,请不要混淆。 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请求方法。 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。 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.[]运算符比点运算符更强大,因为我们也可以访问列表和数组数据,可以将其嵌套,并且当[]的参数不是字符串文字时,将对其进行求值。 If you are using Tomcat, the EL expressions are evaluated usingorg.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate()method.如果使用的是Tomcat,则使用org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate()方法对EL表达式进行求值。 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="/2001/XMLSchema-instance" xmlns="/xml/ns/javaee" xsi:schemaLocation="/xml/ns/javaee /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" "/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的请求时,我们得到如下图所示的输出。

翻译自: /2064/jsp-expression-language-el-example-tutorial

jsp el 表达式

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。