import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class CutStringTag extends TagSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
protected String value;
protected int length;
protected boolean addPoint;
public int doEndTag() throws JspException {
try {
pageContext.getOut().write(getLimitLengthString(value,length,addPoint));
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
private String subStr(String str, int max,boolean isAddpoint){
int sum = 0;
if(str!=null){
StringBuilder sb = new StringBuilder(max);
for (int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if((c & 0xff00) != 0)
sum+=2;
else
sum+=1;
if(sum<=max)
sb.append((char)c);
else
break;
}
if(isAddpoint){
return sb.append("...").toString();
}else{
return sb.toString();
}
}else
return str!=null ? str : "";
}
public String getLimitLengthString(String str, int len,boolean isAddpoint) {
String result ="";
try {
int counterOfDoubleByte = 0;
byte[] b = str.getBytes("gb2312");
if (b.length <= len){
if(isAddpoint){
return str+"...";
}else{
return str;
}
}
for (int i = 0; i < len; i++) {
if (b[i] < 0)
counterOfDoubleByte++;
}
if (counterOfDoubleByte % 2 == 0)
result= new String(b, 0, len, "gb2312");
else
result= new String(b, 0, len - 1, "gb2312");
if(isAddpoint){
result=result + "...";
}
return result;
} catch (Exception ex) {
ex.printStackTrace();
return result;
}
}
public void setLength(int length) {
this.length = length;
}
public void setValue(String value) {
this.value = value;
}
public void setAddPoint(boolean addPoint) {
this.addPoint = addPoint;
}
}