JSTL标签库不能涵括所有的功能,当
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>即JSTL的函数库不能满足时,可以自己搭建标签库
如何搭建自定义标签库
1、新建标签文件 myEL.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>myEL</short-name>
<uri>http://blog.163.com/sender@yeah</uri>
<function>
<description>将Clob转换成String对象</description>
<name>clob2String</name>
<function-class>com.XXX.xxx.util.CommonUtil</function-class>
<function-signature>java.lang.String clob2String(oracle.sql.CLOB)</function-signature>
<example>${myEL:clob2String(clob)}</example>
</function>
</taglib>
2、然后可以在页面直接引用文件:
<%@ taglib uri="/WEB-INF/myEL.tld" prefix="myEL" %>
也可以引用tld中的uri
<%@ taglib uri="http://blog.163.com/sender@yeah" prefix="myEL" %>前提是将这段加入到web.xml中:
<!-- my EL -->
<jsp-config>
<taglib>
<taglib-uri>
http://blog.163.com/sender@yeah
</taglib-uri>
<taglib-location>/WEB-INF/my-el.tld</taglib-location>
</taglib>
</jsp-config>
3、接着就可以正常使用了
${myEL:clob2String(INFO_MAP['INFO_CONTENT'])}
以下自定义方法,慢慢更新
一、CLOB字段转成字符串输出
java代码:
/**
* 将CLOB转成String
*
* @param clob
* 字段
* @return 内容字串,如果出现错误,返回
*/
public static String clob2String(CLOB clob) {
if (clob == null) {
return "";
}
StringBuffer sb = new StringBuffer(65535);// 64K
Reader clobStream = null;
try {
clobStream = clob.getCharacterStream();
char[] b = new char[60000];// 每次获取60K
int i = 0;
while ((i = clobStream.read(b)) != -1) {
sb.append(b, 0, i);
}
} catch (Exception ex) {
sb = null;
} finally {
try {
if (clobStream != null)
clobStream.close();
} catch (Exception e) {
}
}
if (sb == null) {
return "";
} else {
return sb.toString();
}
}
配置tld:见上
方法:
/**
* 中文为2个字符,英文数字
* @param str 要截取的字符串
* @param width 截取的长度
* @param suffix 大于这个长度时后面接的字符串
* @return
*/
public static String cutByChar(String str, int width, String suffix) {
width +=1;
if (str == null || "".equals(str)) {
return "";
}
int d = 0; // byte length
int n = 0; // char length
for (; n < str.length(); n++) {
d = (int) str.charAt(n) > 256 ? d + 2 : d + 1;
if (d > width) {
break;
}
}
if (d > width) {
n = n - suffix.length() / 2;
return str.substring(0, n > 0 ? n : 0) + suffix;
}
return str = str.substring(0, n);
}
标签定义中加入:
<function>
<description>按字符截取字符串,区别中英文</description>
<name>cutByChar</name>
<function-class>com.XXX.xxx.util.UserJstlTaglib</function-class>
<function-signature>java.lang.String cutByChar(java.lang.String,int,java.lang.String)</function-signature>
<example>${myEL:cutByChar(str,40,suff)}</example>
</function>