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_" + property + "'>"); //输出 <td> 标签

out.println("<font class='resizeDivClass'"); //输出 <font> 标签
out.println(" onmousedown='MouseDownToResize(this);');");
out.println(" onmousemove='MouseMoveToResize(this);'");
out.println(" onmouseup='MouseUpToResize(this);'></font>");

out.println("<span onclick=\"sort('"+property + "');\"");
out.println(" style=\"cursor:pointer; \">");
out.println(label); //输出列名

if (property.equals(orderName)) { //如果按本列排序
out.println("<img src='images/'"+orderType +".gif' border=0 />"); //排序图标
}

out.println("</span");
out.println("</td>");
out.println("<script>columns[columns.length]='_id_td_"+property+"';</script>");
}
out.println(" </tr>"); //输出</tr>标签

if (items !=null) {
for (Object obj:(Iterable)items) { //遍历所有数据
out.println(" <tr class=tr_data>"); //输出<tr>标签
for (int i = 0; i < columns.size(); i++) { //遍历所有数据列
Map<String, String> column = columns.get(i);
String property = column.get("property"); //POJO属性名
String getterStyle = toGetterStyle(property); //使首字母大写

try {
String getter = "get" + getterStyle; //get方法名
String is  = "is" + getterStyle; //boolean的getter方法

Method method = null;
try {
method = obj.getClass().getMethod(getter); //getter方法
} catch (Exception e) {
// TODO: handle exception
}

if (method == null) {
method = obj.getClass().getMethod(is); //boolean的getter方法
}

method.setAccessible(true); //是getter方法可见
Object value = method.invoke(obj); //得到getter方法的返回值

out.println("<td><span title='"+value+"'>" + value + "</span></td>"); //输出数据
} catch (Exception e) {
throw new JspException(e);
}
}
out.println(" </tr>");
}
}
out.println("</table>");
} catch (Exception e) {
throw new JspException("Error: "+ e.getMessage());
}
return SKIP_BODY;

}

//使字符串首字母大写
private String toGetterStyle(String column) {
if (column.length() == 1) {
return column.toUpperCase();
}
char ch = column.charAt(0);
return Character.toUpperCase(ch) + column.substring(1);
}

public List<Map<String, String>> getColumns() {
return columns;
}
public void setColumns(List<Map<String, String>> columns) {
this.columns = columns;
}
public Object getItems() {
return items;
}
public void setItems(Object items) {
this.items = items;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}


}

标签类ColumnTag.java的内容为:
package ssh.tag;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public class ColumnTag extends TagSupport{
private String  property; //列对应的POJO属性
private String  label; //列名,在JSP中显示用

public int doStartTag() throws JspException{ //标签开始时执行
if (!(this.getParent() instanceof TableTag)) { //如果不在table标签中
throw new JspException("Column must be inside Table"); //抛出异常
}
Map<String, String> column = new HashMap<String, String>();

column.put("label", label); //保存列名
column.put("property", property); //保存POJO属性名

TableTag tableTag = (TableTag) this.getParent(); //获取父标签table
tableTag.getColumns().add(column); //添加该列
return SKIP_BODY;

}

public int  doEndTag() throws JspException {
return EVAL_PAGE;
}

public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}

}

3、引用自定义标签的jsp文件table.jsp内容为:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="/WEB-INF/lightweight-tag.tld" prefix="nt"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>my tag table</title>
</head>
<body>
<nt:table items="${myPage.list}" url="table.jsp">
<nt:grid label="学号" property="stuId"></nt:grid>
<nt:grid label="姓名" property="stuName"></nt:grid>
<nt:grid label="性别" property="stuSex"></nt:grid>
<nt:grid label="出生年月" property="stuBir"></nt:grid>
<nt:grid label="家庭住址" property="stuAdd"></nt:grid>
</nt:table>
</body>
</html>

这里省去了返回数据的java类,这里的property="stuId",对应的是返回对象的属性名,切勿写错

你可能感兴趣的:(jsp,自定义标签)