jsp自定义标签的应用
下面对自定义标签的应用时通过jsp直接引用的,没有配置在工程中的web.xml中。而且省去了数据返回的java类,只是着重描述了对标签的定义
1、首先定义一个标签的描述文件lightweight-tag.tld,该文件必须放在工程的类路径下,一般和项目的web.xml文件一起就行了。其内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>nt</short-name>
<description>my Form Tag Library Descriptor</description>
<!-- table tag -->
<tag>
<name>table</name>
<tag-class>ssh.tag.TableTag</tag-class>
<body-content>JSP</body-content>
<description>table tag</description>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
</attribute>
</tag>
<!-- column tag -->
<tag>
<name>grid</name>
<tag-class>ssh.tag.ColumnTag</tag-class>
<body-content>JSP</body-content>
<description>column tag</description>
<attribute>
<name>label</name>
<required>true</required>
</attribute>
<attribute>
<name>property</name>
<required>true</required>
</attribute>
</tag>
</taglib>
配置文件中标签类的java类一定要写对
2、标签类TableTag.java的内容为:
package ssh.tag;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
@SuppressWarnings("serial")
public class TableTag extends BodyTagSupport{
private List<Map<String, String>> columns = new ArrayList<Map<String,String>>();
private Object items; //存储数据,可能为集合类型或者数组类型
private String url; //取排序数据的 URL
public int doStartTag() throws JspException{ //标签开始时执行
columns.clear(); //清空colums
return super.doStartTag();
}
@SuppressWarnings("unchecked")
public int doAfterBody() throws JspException{ //标签体结束后执行
try {
BodyContent bc = getBodyContent(); //获取标签体
JspWriter out = bc.getEnclosingWriter();//获取out对象
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
String orderName = request.getParameter("orderName"); //按那一列排序
String orderType = request.getParameter("orderType"); //排序方式
orderType = "desc".equals(orderType) ? "desc" : "asc"; //升序还是降序
out.println("<table id=theObjectTable"); //输出<table>标签
out.println(" class=list_table style='table-layout:fixed;'>");
out.println("<tr class=tr_title >"); //输出<tr>标签
out.println("<script>var colums = []; </script>");
for (int i = 0; i < columns.size(); i++) { //依次输出每一列
Map<String, String> column = columns.get(i); //获取列数据
String label = column.get("label"); //列的名称
String property = column.get("property"); //列对应的 POJO 属性
label = label == null ? property : label; //默认使用属性名作为列名
out.println("<td id='_id_td_