欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

创建自定义标签,struts2

程序员文章站 2022-05-22 14:06:53
...

1,建立自己的标签库tld文件


topdt-tags.tld:

 

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">

<display-name>topdt</display-name>

<tlib-version>1.0</tlib-version>

<short-name>td</short-name>

<tag>

<name>page</name>

<tag-class>com.topdt.frame.web.tags.PageTag</tag-class>

<body-content>JSP</body-content>

<attribute>

<name>template</name>

<required>true</required>

</attribute>

</tag>

<tag>

<name>ss</name>

<tag-class>com.topdt.frame.web.tags.SubStringTag</tag-class>

<body-content>JSP</body-content>

<attribute>

<name>start</name>//这里添加标配的属性

<required>false</required>

<rtexprvalue>false</rtexprvalue>

</attribute>

<attribute>

<name>end</name>

<required>false</required>

<rtexprvalue>false</rtexprvalue>

</attribute>

</tag>

</taglib>

 


2:web.xml文件中加入:

 

 

<jsp-config>

<taglib>

<taglib-uri>/topdt</taglib-uri>

<taglib-location>

/WEB-INF/tlds/topdt-tags.tld

</taglib-location>

</taglib>

</jsp-config>

 

 

3:创建class:

 

 

package com.topdt.frame.web.tags;


import javax.servlet.jsp.JspException;

import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.tagext.BodyTagSupport;


public class SubStringTag extends BodyTagSupport {


private static final long serialVersionUID = 1L;


private int start = 0;//这里对应tld中的属性

private int end = 0;


public int getEnd() {

return end;

}


public void setEnd(int end) {

this.end = end;

}


public int getStart() {

return start;

}


public void setStart(int start) {

this.start = start;

}


public int doEndTag() throws JspException {

try {

JspWriter out = pageContext.getOut();

String b = this.getBodyContent().getString();

b = uToS(b);

if (end < b.length()) {

b = b.substring(start, end)+ "..";

}

out.write(b);

} catch (Exception e) {

throw new JspException(e);

}

return SKIP_BODY; // 不包含主体内容

}


private String uToS(String s) throws Exception {

String[] s3 = s.split(";");

String s1 = "";

if (s3.length > 1) {

for (int i = 0; i < s3.length; i++) {

String[] s2 = s3[i].split("&#");

if (s2.length > 1) {

int v = Integer.parseInt(s2[1], 10);

s1 = s1 + s2[0] + (char) v;

} else {

s1 = s1 + s3[i];

}

}

return s1;

} else {

return s;

}

}

}

 

相关标签: struts2标签