Expression Language Function
java code:
package test.el.function; public class ArithmaticOP { public static int AddInt(int a,int b){ return a+b; } }
mytags.tld
<?xml version="1.0" encoding="UTF-8"?> <taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee web-jsptaglibrary_2_1.xsd"> <tlib-version>1.0</tlib-version> <short-name>mytags</short-name> <function> <name>greet</name> <function-class>test.el.function.Functions</function-class> <function-signature>java.lang.String sayHello()</function-signature> </function> <function> <name>AddInt</name> <function-class>test.el.function.ArithmaticOP</function-class> <function-signature>int AddInt(int ,int )</function-signature> </function> </taglib>
web.xml配置
<jsp-config> <taglib> <taglib-uri>/myTags</taglib-uri> <taglib-location>/WEB-INF/mytags.tld</taglib-location> </taglib> </jsp-config> </web-app>
使用:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/myTags" prefix="mf" %>
//....
${mf:AddInt(11,221) }
</body>
</html>
Expression-Language Functions vs. Custom Tags
As you’ll see in later chapters, the JSP specification provides a powerful custom tag mechanism.
You might ask why you would use tags over functions and vice versa. There are several
factors that can help you to make the choice:
• Is knowledge of the environment required? If the answer is yes, tags are the way to go. A
tag provides easy access to pageContext and other variables; functions do not. To access
these implicit objects within a function, you must pass them in as a parameter.
Do you require iterative behavior over a body? If the answer is yes, you should use a tag.
Functions do not provide functionality to process a body (they don’t have one), whereas
tags do.
• Are you trying to provide a small, reusable piece of functionality that acts on one or
more arguments? If the answer to this is yes, you should use a function. Overall, functions
are much simpler to write than tags; therefore, they provide a great opportunity to
write small, self-contained pieces of functionality.
• Would you like to reuse existing Java code in a web context? If the answer is yes, functions
are ideal. Because functions are no more than static Java methods, you can easily
reuse existing code.
The choice of tags versus functions should be eased by consulting these points, but
it’s worth noting that the true power of the EL becomes evident when it’s combined with custom
tags.