jsp自定义标签封装jqGrid
一、写一个tag的解析类 要继承tagsupport类,复写 dostarttag()或者doendtag就行了。
package com.lubby.tag;
import java.io.ioexception;
import java.util.properties;
import javax.servlet.jsp.jspexception;
import javax.servlet.jsp.tagext.tagsupport;
import org.apache.struts2.servletactioncontext;
import com.lubby.util.propertiesutil;
import com.opensymphony.xwork2.actioncontext;
public class jqgrid extends tagsupport {
private string sql;
@override
public int doendtag() throws jspexception {
try {
propertiesutil.setproperties(sql);
system.out.println(sql);
pagecontext.getout().print("<p id=\"content\"><table id=\"gridtable\" ></table><p id=\"gridpager\"
style=\"height:40px\" ></p></p>");
} catch (ioexception e) {
e.printstacktrace();
}
return eval_page;
}
public void setsql(string sql) {
this.sql = sql;
}
public string getsql() {
return sql;
}
}
二、建立tld文件 (tld的taglib有两种引用,我用的是不用再web.xml配置的那种)
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<taglib xmlns="https://java.sun.com/xml/ns/j2ee"
xmlns:xsi="https://www.w3.org/2001/xmlschema-instance" version="2.0"
xsi:schemalocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<description><![cdata["to make it easier to access dynamic data;"]]></description>
<display-name>permission tags</display-name>
<tlib-version>1.0</tlib-version>
<short-name>lubby</short-name>
<uri>www.lubby.com</uri> //在声明标签的时候使用
<tag>
<name>jqgrid</name> //在jsp中标签名
<tag-class>com.lubby.tag.jqgrid</tag-class> //标签的解释类
<body-content>empty</body-content> //没有body体
<attribute> //设置参数
<name>sql</name> //参数名为sql
<required>true</required> //参数是必须提供的
<fragment>true</fragment>
</attribute>
</tag>
</taglib>
三、在页面上使用标签
1.声明标签
<%@ taglib prefix="s" uri="www.lubby.com"%>
2.使用标签
<s:jqgrid sql = "select t1.id as 编号 ,t1.bussiness as 业务类型 ,t1.customer as 手机号码 ,t1.brand as 品牌 from info t1" />
3.客户端访问时生成的代码是:
<p id="content"><table id="gridtable" ></table><p id="gridpager" style="height:40px" ></p></p>
需要注意的是:jsp自定义标签的原理:jsp最终会转化为servlet,自定义标签也会转化为servlet里面执行代码,servlet会返回给客户端html代码,
客户端(游览器)解释所接收到的html代码。自定义标签由应用服务器转化成html代码。客户端访问的实际上是已经转化的html页面。