其实还没有完全写完,因为现在中文和英文都算是一个字符,但是这是不对的,在页面显示上是两个英文字符算一个汉字的长度.先把这个半成品传上来占个地方吧!下面的实现方式也不复杂,将传入的字符串转成byte后一看其值就知道了,如果是中文的值都是负的,因为字节最高位是1,不多说了,传代码喽~~
package com.deliverik.infogovernor.taglib;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.struts.taglib.TagUtils;
@SuppressWarnings("serial")
public class StrLengthTag extends TagSupport {
// 预期时间
protected String str;
protected int length;
private boolean title;
protected final static String SPAN_START = "<span ";
protected final static String SPAN_END = "</span>";
public int doStartTag() throws JspException {
String retHtml = "";
if(title){
retHtml = SPAN_START + "title=/"" + str + "/">";
}else{
retHtml = SPAN_START + str + "/">";
}
if(str.length()>length){
retHtml+=str.substring(0,length)+"...";
}else{
retHtml += str;
}
retHtml = retHtml + SPAN_END;
TagUtils.getInstance().write(pageContext, retHtml);
return (EVAL_BODY_INCLUDE);
}
/**
* 释放资源
*/
public void release() {
super.release();
str = null;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public boolean isTitle() {
return title;
}
public void setTitle(boolean title) {
this.title = title;
}
}
在tld中的配置如下:
<tag>
<name>strLengthTag</name>
<tag-class>com.deliverik.infogovernor.taglib.StrLengthTag</tag-class>
<body-content>empty</body-content>
<description>string_length</description>
<attribute>
<name>str</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>str</description>
</attribute>
<attribute>
<name>title</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
<description>title</description>
</attribute>
<attribute>
<name>length</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>length</description>
</attribute>
</tag>
页面上的使用方法如下:
<ig:strLengthTag length="14" str="${bean.title}"/>