有时候在JSP页面需要进行一连串的字符串的处理,需要进行自定义EL函数。
先看EL函数的tld文件:
standard.jar下面:
自定义EL函数:
1.编写EL函数(全是public static修饰)
下面这个函数是将一个字符串按后面的格式进行替换
package cn.xm.exam.MyElFunction;/** * 自定义EL函数,方便在JSP中处理一些复杂的字符串替换函数 * ?* @author QiaoLiQiang * @time 2017年10月29日下午9:09:47 */public class MyElFunction { ???/** ????* 将source字符串按照s1-s2替换,例如:s1:1234,s2:ABCD则为将source中1换为A,2换为B``` ????* ?????* @param source ????* ???????????需要被替换的字符串 ????* @param s1 ????* ???????????替换前:1 2 3 4 5 ????* @param s2 ????* ???????????替换后:A B C D E ????* @return ????*/ ???public static String replace(String source, String s1, String s2) { ???????for (int i = 0, length_1 = s1.length(); i < length_1; i++) { ???????????source = source.replace(s1.charAt(i), s2.charAt(i)); ???????} ???????return source; ???}}
2.编写tld文件进行描述(tld文件放在WEB-INF目录下,对刚才编写的函数进行描述,头尾可以参考standard.jar/META-INF/fn.tld)
tld文件加唯一的uri(便于在JSP中引入这个uri)
<?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"> ???<description>JSTL 1.1 functions library</description> ???<display-name>JSTL functions</display-name> ???<tlib-version>1.1</tlib-version> ???<short-name>MyElFunction</short-name> ???<uri>/myfunction</uri> ???<function> ???????<description> ?????将第一个参数中的1234,替换为ABCD ???</description> ???????<name>replace</name> ???????<function-class>cn.xm.exam.MyElFunction.MyElFunction</function-class> ???????<function-signature>String replace(java.lang.String, java.lang.String, ???????????java.lang.String) ???????</function-signature> ???????<example> ??????${replace("126352","1234","ABCD")} ???</example> ???</function></taglib>
3.JSP中使用
<%@ page language="java" contentType="text/html; charset=UTF-8" ???pageEncoding="UTF-8"%><%@taglib uri="/myfunction" prefix="my"%><!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>Insert title here</title></head><body>${my:replace("12345","1234","ABCD") }</body></html>
结果:
4.JSP中结合EL函数进行使用
<%@ page language="java" contentType="text/html; charset=UTF-8" ???pageEncoding="UTF-8"%><%@taglib uri="/myfunction" prefix="my"%><!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>Insert title here</title><% ???request.setAttribute("test", "132");%></head><body>${my:replace(test,"1234","ABCD") }</body></html>
结果:
ACB
解析:上述自定义的函数从域中取出test,然后对test进行替换
[JSP]自定义EL函数以及使用
原文地址:http://www.cnblogs.com/qlqwjy/p/7751466.html