Javaweb Learning Summary (29)--el expression

Source: Internet
Author: User
Tags tld

Javaweb Learning Summary (29)--el Expression I. Introduction to EL expression

EL full name is Expression Language. El main functions:
1. Access to Data
El expressions are primarily used to replace script expressions in JSP pages to retrieve Java objects from various types of Web domains and get data. (objects in a web domain, accessing JavaBean properties, accessing the list collection, accessing the map collection, accessing an array)
2. Perform operation
The EL expression allows you to perform some basic relational, logical, and arithmetic operations on a JSP page to accomplish some simple logic operations in a JSP page. ${user==null}
3. Get common objects for web development
EL expressions define implicit objects that make it easy for web developers to get a reference to a common Web object to get the data in those objects.
4. Calling the Java method
The EL expression allows the user to develop a custom El function that invokes a method of the Java class through an El expression in a JSP page.

1.1. Access to Data

Get data syntax using el expression: "${identifier}"
The EL expression statement, when executed, invokes the Pagecontext.findattribute method, using the identifier as the keyword, to find the corresponding object from page, request, session, and application four fields, and then returns the corresponding object. Returned "" (Note that it is not NULL, but an empty string).

El expressions can easily get JavaBean properties, or get data from arrays, Collection, and map type collections

An example of an El expression fetching data:

 1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 <% @taglib uri= "http://java.sun.com/ Jsp/jstl/core "prefix=" C "%> 3 <% @page import=" Me.gacl.domain.Person "%> 4 <% @page import=" Me.gacl.domain.Address "%> 5 <! DOCTYPE html> 6 

The results are as follows:

  

1.2. Perform operation

Syntax: ${expression},el expression supports the following operators:

1. Relational operators

  

2. Logical operators:

  

  3, empty operator : Checks whether the object is null (NULL)

  4, two-tuple expression : ${user!=null?user.name: ""}
  5, [] and. Number operator

Use the EL expression to perform an operation example:

 1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 <% @taglib uri= "http://java.sun.com/ Jsp/jstl/core "prefix=" C "%> 3 <% @page import=" Me.gacl.domain.User "%> 4 <! DOCTYPE html> 5 

The results of the operation are as follows:

  

1.3. Get common objects for web development

The EL expression language defines 11 hidden objects, which make it easy to get some common objects in web development and read the data of those objects.
Syntax:${Implicit object name}: Getting a reference to an object

Serial number Implied object name Description
1 PageContext Corresponds to the PageContext object in the JSP page (note: The PageContext object is taken.) )
2 Pagescope Represents the Map object in the page field for saving properties
3 Requestscope Represents the Map object in the Request field for saving properties
4 Sessionscope Represents the Map object in the Session field for saving properties
5 Applicationscope Represents the Map object in the Application field for saving properties
6 Param Represents a map object that holds all the request parameters
7 Paramvalues Represents a map object that holds all the request parameters, and it returns a string[for a request parameter]
8 Header Represents a map object that holds all HTTP request header fields, note: If there is "-" in the header, example accept-encoding, header["accept-encoding"]
9 Headervalues Represents a map object that holds all HTTP request header fields, and returns a string[] array for a request parameter. Note: If there is "-" in the head, example accept-encoding, headervalues["accept-encoding"]
10 Cookies Represents a map object that holds all cookies
11 Initparam Represents a map object that holds all the Web application initialization parameters

To test 11 implicit objects in an El expression:

 1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 <! DOCTYPE html> 3 

The code for Registerservlet is as follows:

 1 package Me.gacl.web.controller; 2 3 Import java.io.IOException; 4 Import javax.servlet.ServletException; 5 Import Javax.servlet.http.HttpServlet; 6 Import Javax.servlet.http.HttpServletRequest; 7 Import Javax.servlet.http.HttpServletResponse; 8 9 public class Registerservlet extends HttpServlet {10 */11 * Methods of handling user registration */13 public void doget (HTT Pservletrequest request, HttpServletResponse response) throws Servletexception, IOException {15//1, Receive parameters: String userName = Request.getparameter ("UserName"), 17/**18 * 2, direct jump back to/eldemo03.jsp page, no use R Equest.setattribute ("UserName", UserName) stores the userName in the Request object 19 * But you can use eldemo03.jsp on the ${param.username page to get to req     The value of the username parameter in the Uest object is */21 request.getrequestdispatcher ("/eldemo03.jsp"). Forward (request, response); 22 }23 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexc Eption, IOException {Doget (request, response); 27}28} 

The test results are as follows:

  

Attention:
  Test header and Headervalues, if there is "-" in the head, example accept-encoding, then header["accept-encoding"], headervalues["accept-encoding"]
When testing a cookie, the example ${cookie.key} takes a cookie object, such as the name and value of the access cookie, to be ${cookie.key.name} or ${cookie.key.value}

1.4. Invoking the Java method with El

The EL expression syntax allows developers to develop custom functions to invoke methods of the Java class. Syntax: ${prefix:method (params)}
The static method of a Java class can only be called in an El expression, and the static method of the Java class needs to be described in the TLD file before it can be called by an El expression.
The El Custom function is used to extend the functionality of the El expression, allowing the El expression to do what ordinary Java program code can do.

1.5. EL function Development Steps

In general, the development and application of El Custom functions consists of the following three steps:
1. Write a static method of a Java class
2. Write a tag library descriptor (TLD) file that describes the custom function in the TLD file.
3. Import and use custom functions in JSP pages

Example: Developing an El function that escapes an HTML tag

1, write the HTML Escape processing tool class, the tool class added to the HTML tag to escape the static processing method, as follows:

 1 package me.gacl.util; 2 3/** 4 * @ClassName: Htmlfilter 5 * @Description: HTML Escape Processing Tool Class 6 * @author: Aloof and pale Wolf 7 * @date: 2014-8-27 12:09:15 8 * 9 * * public class Htmlfilter {/**13 * @Method: Filter14 * @Description: Static method, HTML tag escape processing * @Anthor : Aloof and pale wolf *17 * @param message to escape content * @return escaped content */public static string filter (String mess Age) {if (message = = NULL) (null); [n] char content[] = new Char[message.lengt H ()];26 message.getchars (0, Message.length (), content, 0); StringBuffer result = new StringBuffer (conten             T.length + (int i = 0; i < content.length; i++) {switch (Content[i]) {30 Case ' < ': Result.append ("&lt;"); break;33 case ' > ': Result.append ("&gt;"); break;36 case ' & ': PNs result.append ("&AMp;amp; "); break;39 case ' "': Result.append (" &quot; "); break;42 default:43 result.append (Content[i]); 44}45}4 6 return (result.tostring ()); 47}48}

2. Write a tag library descriptor (TLD) file in the Web-inf directory and describe the custom function in the TLD file

  

The code for ELFUNCTION.TLD is as follows:

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <taglib version= "2.0" xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE" 3 xml Ns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://java.sun.com/xml/ns/j2ee Web-jsptaglibrary_2_0.xsd "> 4 <tlib-version>1.0</tlib-version> 5 <short-name>el function</   Short-name> 6 <!--7 reference URI for the custom El function library, 8 can be referenced in JSP pages: <% @taglib uri= "/elfunction" prefix= "FN"%> 9          -->10 <uri>/elfunction</uri>11 <!--<function> element is used to describe an El custom function-->13 <function>14         <description>html label Escape processing method </description>15 <!--<name> child elements are used to specify the name of the El Custom function-->16 <name>filter</name>17 <!--<function-class> child elements are used to specify the full Java class name-->18 <function-cla ss>me.gacl.util.htmlfilter</function-class>19 <!--<function-signature> child elements are used to specify the signature of a static method in a Java class. 20 The method signature must indicate the return value type of the method and the type of each parameter, separated by commas. -->21 <function-signature>java.lang.string Filter (java.lang.String) </function-signature>22 </f Unction>23 </taglib>

3. Import and use custom functions in JSP pages

1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 <%--introduced El Custom function library--%> 3 <% @taglib u Ri= "/elfunction" prefix= "FN"%> 4 <! DOCTYPE html> 5 

The results of the operation are as follows:

  

1.6, the development of El function considerations

After you have written the tag library profile, you need to place it in any subdirectory other than the classes and LIB directories in the <web app >\web-inf directory or Web-inf directory.
The <uri> element in the TLD file uses the URI of the specified TLD file, which in the JSP file needs to be introduced into the tag library description file.
The <function> element is used to describe an El custom function, where:
The <name> child element is used to specify the name of the El Custom function.
The <function-class> child element is used to specify the full Java class name,
The <function-signature> child element is used to specify the signature of a static method in a Java class, and the method signature must indicate the type of the method's return value and the type of each parameter, separating each parameter with a comma.

1.7. El Precautions

The EL expression is a technique in the JSP 2.0 specification. Therefore, if you want to parse the EL expression correctly, you need to use a Web server that supports servlet2.4/jsp2.0 technology.
Note: Some tomcat servers cannot use El expressions
(1) Upgrade to TOMCAT6
(2) Add <%@ page iselignored= "false" in the JSP%>

1.8. El expression reserved keyword

  

The so-called reserved word means that when a variable is named, it should avoid the above name, so as to avoid errors when the program compiles, so many summaries of the contents of the El expression.

Javaweb Learning Summary (29)--el expression

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.