首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

taglib-文本切割

2012-10-07 
taglib--文本切割返回 常用taglib及用法?1. tld文件配置package com.neu.edu.utils.mytaglibimport jav

taglib--文本切割

返回 常用taglib及用法>>

?

1. tld文件配置

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>

?

返回>>

热点排行