Javaweb El Expression instance detailed _java

Source: Internet
Author: User
Tags arithmetic logical operators reserved tld stringbuffer

El full name Expression Language (expression language), is one of the most important features of jsp2.0, can use El expressions to access data in the application to eliminate Java script in JSP pages.

Syntax of an EL expression

Expression such as x+y can be written as {x+y}

Keywords in El

The following are keywords in El that they cannot be used as identifiers:

And,eq,gt,true,instanceof,or,ne,le,false,empty,not,lt,ge,null,div,mod

Introduction of El Expressions

EL full name is Expression Language. El main function:

  1, access to data

El expressions are used primarily to replace script expressions in JSP pages to retrieve Java objects and fetch data from various types of Web domains. (objects in a web domain, accessing JavaBean properties, accessing the list collection, accessing the map collection, accessing the array)

 2. Perform operation

Using El expressions, you can perform some basic relational, logical, and arithmetic operations in a JSP page to complete some simple logical operations in a JSP page. ${user==null}

  3, get the Common object of web development

EL expressions define implicit objects that make it easy for web developers to get references to web-common objects and get the data from those objects.

 4. Invoke Java method

El expressions allow users to develop custom El functions to invoke methods of Java classes in a JSP page through an El expression.

1.1, access to data

Get data syntax using el expression: "${identifier}"

When the EL expression statement executes, it invokes the Pagecontext.findattribute method, finds the corresponding object from page, request, session, application four domains, and finds the corresponding object, using the identifier as the keyword. Returns "" (note, not NULL, but an empty string) if it is not found.

El expressions can easily get JavaBean properties, or get data for arrays, Collection, map-type collections

El expression Gets an example of the data:

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-"%> <% @taglib uri= "http://java.sun.com/jsp/ Jstl/core "prefix=" C "%> <% @page import=" Me.gacl.domain.Person "%> <% @page import=" me.gacl.domain.Address "%> <! 
DOCTYPE html>  

The operation effect is as follows:


1.2. Perform operation

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

1. Relational operators

2. Logical operators:

  

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

4, two-yuan expression: ${user!=null?user.name: ""}

5, [] and. Number operator

Using El expressions to perform an operation example:

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-"%> <% @taglib uri= "http://java.sun.com/jsp/ Jstl/core "prefix=" C "%> <% @page import=" Me.gacl.domain.User "%> <! DOCTYPE html>  

The results of the operation are as follows:

  

1.3. Get the common object of web development

There are 11 suppressed objects defined in the El Expression language that make it easy to get some common objects in web development and read the data for those objects.

Syntax:${Implicit object name}: getting references to Objects


To test 11 implicit objects in an El expression:

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-"%> <! DOCTYPE html>  

The code for Registerservlet is as follows:

Package Me.gacl.web.controller;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Registerservlet extends HttpServlet {
* 
* * Process User Registration Method * * Public
void Doget ( HttpServletRequest request, HttpServletResponse response)
throws Servletexception, IOException {
//, receive parameters
String userName = Request.getparameter ("UserName");
/**
*, jump back to/eldemo.jsp page without using Request.setattribute ("UserName", UserName) to store userName in the Request object
* However, in the eldemo.jsp page you can use ${param.username} to obtain the value of the username parameter in the Request object
/Request.getrequestdispatcher ("/ Eldemo.jsp "). Forward (request, response);
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
doget (request, response);
}
}

The test results are as follows:

Attention:

When testing header and Headervalues, if there is a "-" in the head, the example accept-encoding, then header["accept-encoding", headervalues["accept-encoding"]

When testing cookies, example ${cookie.key} takes a cookie object, such as accessing the name and value of the cookie, ${cookie.key.name} or ${cookie.key.value}

1.4. Invoke Java method with El

The EL expression syntax allows developers to develop custom functions to invoke methods of Java classes. Syntax: ${prefix:method (params)}

Only static methods of Java classes are invoked in El expressions, and the static method of this Java class needs to be described in the TLD file before it can be invoked by an El expression.

El custom functions are used to extend the functionality of El expressions, allowing El expressions to perform the functions that ordinary Java program code can accomplish.

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 Java class

2. Write tag Library descriptor (TLD) file to describe the custom function in the TLD file.

3. Import and use custom functions in JSP pages

Example: Developing an El function that escapes HTML tags

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

Package me.gacl.util;
/**
* @ClassName: Htmlfilter
* @Description: HTML escape Processing Tool class
* @author: Aloof Wolf
* @date:--Morning::
*
*/< C8/>public class Htmlfilter {
/**
* @Method: Filter
* @Description: Static method, HTML tag escape processing
* @Anthor: Lonely Wolf c13/>*
* @param message The content to be escaped
* @return the escaped content
* 
/public static String filter (String message) {
   IF (message = = NULL) return
(null);
Char content[] = new Char[message.length ()];
Message.getchars (, Message.length (), content,);
StringBuffer result = new StringBuffer (content.length +);
for (int i =; i < content.length; i++) {
switch (Content[i]) {case
' < ':
result.append ("<"); 
   
    break;
Case ' > ':
result.append (">");
break;
Case ' & ':
result.append ("&");
break;
Case ' "':
result.append (" ");
break;
Default:
result.append (Content[i]);
}
Return (result.tostring ());
}

   

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

The code for ELFUNCTION.TLD is as follows:

<?xml version= "." encoding= "utf-?> <taglib". "Version=" xmlns= "Http://java.sun.com/xml/ns/jee" Http://www.w.org//XMLSchema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/jee web-jsptaglibrary__.xsd 
"> <tlib-version>.</tlib-version> <short-name>el function</short-name> <!-- Customize the reference URI for the El function library, which can be referenced in a JSP page: <% @taglib uri= "/elfunction" prefix= "FN"%>--> > <!--<function> element is used to describe an El Custom function--> <function> <description>html tag Escape processing </ description> <!--<name> child elements to specify the name of the El Custom function--> <name>filter</name> <!--<
The function-class> child element is used to specify the complete Java class name--> <function-class>me.gacl.util.HtmlFilter</function-class> <!--<function-signature> child elements are used to specify the signature of a static method in a Java class, and the method signature must indicate the return value type of the method and the type of each parameter, separated by commas. --> <function-signature>java.lang.string Filter (java.lang.String) </function-signature> </  Function> </taglib>

3. Import and use custom functions in JSP pages

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-"%> <%--
introduce el Custom function library--%>
<%@ Taglib uri= "/elfunction" prefix= "FN"%>
<! DOCTYPE html>

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.