返回 常用taglib及用法>>
?
1. tld文件配置
<tag> <name>stringCut</name> <tag-class>com.neu.edu.utils.mytaglib.StringCutTag</tag-class> <body-content>JSP</body-content> <attribute> <name>length</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>str</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>?
2. 实现
package com.neu.edu.utils.mytaglib;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.xiaonei.wap.framework.util.WapStringUtils;
public class StringCutTag extends BodyTagSupport {
private int length = 0;
private String str = "";
public void setLength(int length) {
this.length = length;
}
public void setStr(String str) {
this.str = str;
}
@Override
public int doAfterBody() throws JspException {
BodyContent bodyContent = getBodyContent();
String content = bodyContent.getString();
String outStr = cut(content, length);
JspWriter out = bodyContent.getEnclosingWriter();
try {
out.write(outStr);
} catch (IOException e) {
e.printStackTrace();
}
return super.doAfterBody();
}
@Override
public int doStartTag() throws JspException {
if(StringUtils.isNotBlank(str)){
String outStr = cut(str, length);
try {
pageContext.getOut().print(outStr);
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
} else
return super.doStartTag();
}
private String cut(String str, int length) {
if (StringUtils.isBlank(str) || length <= 0) return "";
if (str.length() <= length) return str;
int tlength = 0;
int maxLength = length * 2;
int i;
for (i = 0; i < str.length() && tlength <= maxLength; i++) {
if (CharUtils.isAscii(str.charAt(i))) ++tlength;
else tlength += 2;
}
if (i == str.length() && tlength <= maxLength) return str;
maxLength -= 2;
while (tlength > maxLength) {
if (CharUtils.isAscii(str.charAt(i - 1))) --tlength;
else tlength -= 2;
--i;
}
return str.substring(0, i) + "...";
}
}
?
3. 使用
?
??? <renren-wap:stringCut length="28">${content}</renren-wap:stringCut>
?
返回>>