在使用
JSTL
标签的截取字符串函数时有点不爽
!
当汉字、字母、数字混合在一个字符串中进行统计长度或截取时,它会把汉字、字母、数字作为同一长度进行截取!如:
String str = “abc
中国
123”;
${fn:substr(str,0,6)}
的结果就是:
abc
中国
1
这让我们用起来很不舒服,特别是在进行列表时,截取同样的长度,如果哪个包含的字母或数字较多,就会看起来特别短。
为此,我把
JSTL
源代码下载下来,增加了一个函数
getLimitStr(String,int).
这个函数的作用是对
str
进行前
len
个长度的字符,如果
str
的长度大于
len,
则用
”…”
结尾。
具体步骤:
一、在
org.apache.taglibs.standard.functions
包的
Functions.java
类中加如下代码:
public static String getLimitStr( String str,int len,String limitStr){
try{
if(str==null) return "";
int counterOfDoubleByte = 0;
byte[] b = str.getBytes("gb2312");
int holdLen = limitStr.length(); //分隔符占多少位,如"..."就是占3位
if(b.length <= len)
return str;
for(int i = 0; i < len-holdLen; i++){
if(b[i] < 0)
counterOfDoubleByte++;
}
if(counterOfDoubleByte % 2 == 0)
return new String(b, 0, len - holdLen, "gb2312")+limitStr;
else
return new String(b, 0, len - holdLen-1, "gb2312")+limitStr;
}catch(Exception ex){
return "";
}
}
二、在
fn.tld
中加:
<
function
>
<
description
>
Removes white spaces from both ends of a string.
</
description
>
<
name
>
getLimitStr
</
name
>
<
function-class
>
org.apache.taglibs.standard.functions.Functions
</
function-class
>
<
function-signature
>
java.lang.String getLimitStr(java.lang.String,int)
</
function-signature
>
<
example
>
Name: ${fn.getLimitStr(str,20)}
</
example
>
</
function
>
三、把
Functions.class
和
fn.tld
压回
standard.jar
中。(两个必须都同时这样做)
四、本例使用的是
JSTL1.1
五、在编译
JSTL
源码时,需要在
apache
网站下载
xalan-j_2_7_0.jar
这个包。