Home  >  Article  >  Java  >  Share a summary of EL expressions in JSP page technology

Share a summary of EL expressions in JSP page technology

Y2J
Y2JOriginal
2017-04-28 10:04:031620browse

This article mainly introduces the concept, role and use of EL expressions and syntax of JSP page technology in java. Friends in need can refer to

1. Concept

Expression Language (Expression Language), or EL expression, or EL for short, is a special general-purpose programming language in Java, borrowed from JavaScript and XPath. Its main function is to embed Java Web applications into web pages (such as JSP) to access the context of the page and objects in different scopes, obtain the values ​​of object attributes, or perform simple calculations or judgment operations. When EL gets certain data, it will automatically convert the data type.

Main functions:

1) Obtain data

EL expressions are mainly used to replace script expressions in JSP pages Formula 332000003288cabbdff89f9a8e5a919b to retrieve java objects and obtain data from various types of web domains. (Objects in a certain web domain, access Javabean attributes, access list collections, access map collections, access arrays)

2) Perform operations

Use EL expression Formulas can perform some basic relational operations, logical operations and arithmetic operations in JSP pages to complete some simple logical operations in JSP pages. ${user==null}

3) Obtain common objects EL for web development

Expressions define some implicit objects. Using these implicit objects, web development People can easily obtain references to common objects on the web and obtain the data in these objects.

4) Call Java methods

EL expression allows users to develop custom EL functions to call methods of Java classes through EL expressions in JSP pages.

Note: d9c609a8bf8eb44279d32fb2fbb5ee7a Indicates whether to disable EL language, TRUE means prohibited. FALSE means not prohibited.JSP2.0 The EL language is enabled by default in

2. Syntax

Starts with "${" and ends with "}":

${EL expression}

Example:

${ str } //输出字符串变量str的值
${ 1 + 2 } //输出1+2的结果
${ user.name} //输出user对象的name属性 访问对象user的getName()方法以得到name成员的值。
${user[“name”] } //同上
${ sessionScope[“user”].name } //同上
${list[0]} //访问list对象的第一项。
${map[“key”]} //访问map指定键的值。

3. Fetch operator

EL provides. and [ ] operators to access data:

. Access a Bean property or a mapping entry such as: ${ user.name}

[ ] You can access a collection or an array Elements and Bean properties can also be accessed. For example: ${ arr[0].name}

Similarities and differences:

Same: can be used to access the properties of the object

Differences: When you want If the accessed attribute name contains some special characters, such as . or ? or - and other non-letter or numeric symbols, you must use [], such as user.my-name should be {user["my-name" ]}

4. Operators:

● There are five arithmetic operators: +, -, *,/or p, % or mod

● There are six relational operators: == or eq, != or ne, 75390af9afb064fc760e18f0127d36eb or gt, cb290a39e15405e6b4be1819368d4029= or ge

● There are three logical operators: && or and, || or or, ! or not

● There are three other operators: Empty operator, conditional operator, () operator

5. Hidden objects

JSP EL supports the hidden objects listed in the following table:

You can use these objects like variables in expressions.

Group by function as follows:

1) Access parameter value:

param: The corresponding single request parameter name can be obtained value. For example: $(param.name) is equivalent to request.getParameter (name).

paramValues: The corresponding string array can be obtained according to the parameter name. For example: ${paramvalues.name) is equivalent to request.getParamterValues(name).

Note: The param object returns a single string, while the paramValues ​​object returns an array of strings.

2) Access header information

header: You can obtain the corresponding single string header value in the request header information. The expression header.name is equivalent to request.getHeader(name). Such as {header[“user-agent”]}. The user-agent header can be printed out.

headerValues: The request header name can be mapped to a numerical array. For example, ${headerValues.name} is equivalent to request.getHeaderValues(name).

Note: The header object returns a single value, while headerValues ​​returns a string array.

3) Access other details about the user request or page

pageContext:

pageContext.request | Get request Object {pageContext.session} |Get the session object

pageContext.request.queryString|Get the parameter string of the request {pageContext.request.requestURL} |Get the URL of the request, but does not include the parameter string of the request

pageContext.request.contextPath | The name of the webapplication served {pageContext.request.method} | Get the HTTP method (GET, POST)

pageContext.request.protocol | Get the protocol used ( HTTP/1.1, HTTP/1.0){pageContext.request.remoteUser} |Get user name

pageContext.request.remoteAddr|取得用户的IP地址{pageContext.session.new} |判断session是否为新的,所谓新的session,表示刚由 server产生而client尚未使用 的

pageContext.session.id|取得session的ID{pageContext.servletContext.serverInfo}|取得主机端的服务信息

4)访问不同作用域的变量,如 Web 上下文、会话、请求、页面:

pageScope :取得页面范围的值

如用 pageScope.objectName访问一个JSP中页面范围的对象,还可以使用{pageScope.objectName.attributeName} 访问对象的属性。

requestScope:取得请求范围的变量值

该对象允许访问请求对象的属性。如用 requestScope.objectName访问一个JSP请求范围的对象,还可以使用{requestScope.objectName.attributeName} 访问对象的属性。

sessionScope:取得会话范围的变量值

该对象允许访问会话对象的属性。如:$sessionScope.name}

applicationScope:取得应用程序范围的变量值

该隐式对象允许访问应用程序范围的对象

5) 访问Cookie中的值

如要取得cookie中有一个设定名称为username的值,可以使用${cookie.username} 来取得它。

六、使用sun提供的标准 EL函数库

由于在JSP页面中显示数据时,经常需要对显示的字符串进行处理,SUN公司针对于一些常见处理定义了一套EL函数库供开发者使用。

这些EL函数在JSTL开发包中进行描述,因此在JSP页面中使用SUN公司的EL函数库,需要导入JSTL开发包,并在页面中导入EL函数库。

使用EL函数库

1) 导入 jstl jar包

2) 在相应的jsp页面添加引用

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*" %>
<!--导入需要使用taglib指令 --> 
 
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!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>el function demo</title>
</head>
<body>
 
   <%
       String[] strs = {"a","b","c"};//定义一个字符数组
       List list = new ArrayList();//定义一个list集合
       list.add("a");//向集合中添加一个字符
       pageContext.setAttribute("arr", strs);//将字符数据以arr的名字保存在page域中
       pageContext.setAttribute("list", list);//将list集合以list的名字保存在page域中
    %>
 
${fn:length(arr) }<br/><!--3-->
${fn:length(list) }<br/><!--1-->
${fn:toLowerCase("Hello") }<br/> <!-- hello -->
${fn:toUpperCase("Hello") }<br/> <!-- HELLO -->
${fn:contains("abc", "a")}<br/><!-- true -->
${fn:containsIgnoreCase("abc", "Ab")}<br/><!-- true -->
${fn:contains(arr, "a")}<br/><!-- true -->
${fn:containsIgnoreCase(list, "A")}<br/><!-- true -->
${fn:endsWith("Hello.java", ".java")}<br/><!-- true -->
${fn:startsWith("Hello.java", "Hell")}<br/><!-- true -->
${fn:indexOf("Hello-World", "-")}<br/><!-- 5 -->
${fn:join(arr, ";")}<br/><!-- a;b;c -->
${fn:replace("Hello-World", "-", "+")}<br/><!-- Hello+World -->
${fn:join(fn:split("a;b;c;", ";"), "-")}<br/><!-- a-b-c -->
${fn:substring("0123456789", 6, 9)}<br/><!-- 678 -->
${fn:substring("0123456789", 5, -1)}<br/><!-- 56789 -->
${fn:substringAfter("Hello-World", "-")}<br/><!-- World -->
${fn:substringBefore("Hello-World", "-")}<br/><!-- Hello -->
${fn:trim("   a b c   ")}<br/><!-- a b c -->
${fn:escapeXml("<html></html>")}<br/> <!-- <html></html> --> 
</body>
</html>

函数库详细介绍

String toUpperCase(String input):把字符串参数转换成大写,并返回

String toLowerCase(String input):把字符串参数转换成小写,并返回

int indexOf(String input, String substring):返回input中substring出现的索引位置

boolean contains(String input, String substring):查看input中是否包含substring,包含返回true,否则返回false;

boolean containsIgnoreCase(String input, String substring):在忽略大小写的情况下,查看input中是否包含substring,包含返回true,否则返回false

boolean startsWith(String input, String substring):判断input是否是以substring为前缀,如果是就返回true,否则就返回false

boolean endsWith(String input, String substring):判断input是否是以substring为后缀,如果是就返回true,否则就返回false

String substring(String input, int beginIndex, int endIndex):以beginIndex为开始值,endIndex为结束值,在input上截取子串

String substringAfter(String input, String substring):获取input中,substring所在位置后面的字符串

substringBefore(String input, String substring):获取input中,substring所在位置前面的字符串 String escapeXml(String input):把input中“a49f0050de68a7521e560d1cb8dde1e7“、”&“、”'“、“””进行转义;

String trim(String input):去除input中的前后空格;

String replace(String input, String substringBefore, String substringAfter):将input中的substringBefore替换成substringAfter;

String[] split(String input, String delimiters):以delimiters为标识分割input,返回一个字符串数组;

int length(Object obj):可以获取字符串、数组、各种集合的长度;

String join(String array[], String separator):将array数组中的元素以separator连接起来,返回一个字符串

七、EL调用自定义函数 (调用普通类的静态方法)

EL很强大,除了使用SUN提供的标准EL函数库外,还可以调用自定义函数:

● EL表达式语法允许开发人员开发自定义函数,以调用Java类的方法。语法:${prefix:method(params)}

● 在EL表达式中调用的只能是Java类的静态方法,这个Java类的静态方法需要在TLD文件中描述,才可以被EL表达式调用。

● EL自定义函数用于扩展EL表达式的功能,可以让EL表达式完成普通Java程序代码所能完成的功能。

EL Function开发步骤

只要实现以下三个步骤就可以在静态页面中用${prefix:method(params)} 调用自定义function了

编写一个Java类的静态方法

编写标签库描述符(tld)文件,在tld文件中描述自定义函数。

在JSP页面中导入和使用自定义函数

下面来个案例:

1)编写一个Java类的静态方法

public class GetMax {
  public static int togetMax(int a, int b){
    return a>b?a:b;
  }
}

2)编写标签库描述符(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">  
  <tlib-version>1.0</tlib-version><!-- 定义的版本 --> 
  <short-name>mytaglib</short-name><!--这个名字可以随便取,尽量与文件名相同,这样我们知道文件在哪儿 并与prefix对应--> 
  <uri>http://localhost:8080/springmvc-1</uri><!-- 这个地址是随便取得。到时候jsp页面引入这个地址 -->          
  <function><!-- 定义函数 --> 
    <name>toGetMax</name>
    <function-class>elfunction.GetMax</function-class><!-- 定义函数的类全名称 --> 
    <function-signature>int toGetMax(int,int)</function-signature> 
    <!--说明 返回值类型 函数名 以及 参数类型 --> 
  </function> 
</taglib>

3)在web.xml中指定tld文件的位置(这步可以省略,因为应用会自动找到 /WEB-INF/下的tld文件)

<jsp-config> 
    <taglib> 
      <!-- 此处uri可以自己随便定义,但后面用时一定与这里一样 --> 
      <taglib-uri> 
        http://localhost:8080/springmvc-1
      </taglib-uri> 
      <!-- tld文件的路径 --> 
      <taglib-location> 
        /WEB-INF/tags/mytaglib.tld
      </taglib-location> 
    </taglib> 
  </jsp-config>

4)在JSP页面中导入和使用自定义函数

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 
<%@ taglib uri="http://localhost:8080/springmvc-1" prefix="mytaglib"%> 
<!-- prefix 是前缀的意思,应与mytaglib.tld中的<short-name>对应 -->
 
<!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>custom EL function test</title>
</head>
<body>
  1和2求最大值 = ${mytaglib:toGetMax(1,2)}
</body>
</html>

运行截图

The above is the detailed content of Share a summary of EL expressions in JSP page technology. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn