一、写XML文件util.tld:
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>util</short-name>
<uri>http://aircom.com/taglib/util</uri>
<display-name>utlitytags</display-name>
<description>custom web utility tags</description>
<tag>
<name>replace</name>
<tagclass>com.aircom.zzy.tag.ReplaceTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>oldstr</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>length</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>replacechar</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
二,写类文件ReplaceTag.java
import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class ReplaceTag extends TagSupport {
private static final long serialVersionUID = -749340409045152888L;
private String oldstr;
private int length;
private String replacechar;
public int doEndTag() throws JspTagException {
JspWriter out = pageContext.getOut();
try {
out.println(getSubStr(oldstr, length, replacechar));
} catch (IOException e) {
throw new JspTagException(e);
}
return EVAL_PAGE;
}
/** *//**
* replace string
* @param str
* @param cutCount set byte
* @return
*/
public String getSubStr(String str, int cutCount, String repstr){
if (str == null)
return "";
String resultStr = "";
String newString = "";
if(str.getBytes().length<=cutCount){
int cutLength = cutCount-str.getBytes().length;
for(int i=0;i<cutLength;i++)
newString += " ";
return str + newString + " ";
}
char[] ch = str.toCharArray();
int count = ch.length;
int strBLen = str.getBytes().length;
int temp = 0;
for (int i = 0; i < count; i++){
resultStr += ch[i];
temp = resultStr.getBytes().length;
if (temp >= cutCount && temp < strBLen){
resultStr += " " + repstr + repstr + repstr;
break;
}
}
return resultStr;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getOldstr() {
return oldstr;
}
public void setOldstr(String oldstr) {
this.oldstr = oldstr;
}
public String getReplacechar() {
return replacechar;
}
public void setReplacechar(String replacechar) {
this.replacechar = replacechar;
}
}
三,JSP页面调用:
<%@ taglib prefix="s" uri="/struts-tags"%>
<util:replace oldstr="${caption}" length="8" replacechar="."></util:replace>
作用:当文字长度超过8个字符时,用属性replacechar的值代替。