您的位置:首页 > Web前端 > JavaScript

自定义jsp标签

2016-06-10 12:54 369 查看
1.新建一个类继承自TagSupport、BodyTagSupport或实现Tag接口

//对应一个jsp标签
public class MyTag extends TagSupport {
private JspWriter writer = null;
  //对应到jsp标签的属性
private String showMsg;
//遇到<调用
//合法返回值EVAL_BODY_INCLUDE(显示标签体内容)与SKIP_BODY(不显示标签体内容)
@Override
public int doStartTag() throws JspException {
return super.doStartTag();
}
  //遇到>调用
  //合法返回值EVAL_PAGE(继续处理后续标签)与SKIP_PAGE(不处理后续表情)
@Override
public int doEndTag() throws JspException {
    //获得PageContext对象
writer = this.pageContext.getOut();
try{
writer.write(showMeg);
}catch (IOException ie){
ie.printStackTrace();
}
return super.doEndTag();
}
  //必须提供setter方法
public void setShowMsg(String showMeg) {
this.showMeg = showMeg;
}
}


新建一个myxxx.tld文件,放于WEB-INF目录/其子目录下,用于映射关系

<?xml version="1.0" encoding="ISO-8859-1"?>

<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 http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1">

<tlib-version>1.0</tlib-version>
<short-name>myshortname</short-name>
<uri>http://mycompany.com</uri>
<!--加入自定义标签的定义-->
<tag>
<name>my1</name>
<tag-class>tag.MyTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>showMsg</name>
       <!--配置是否必须-->
<required>true</required>
</attribute>
</tag>

</taglib>


在web.xml文件中配置标签库uri

<jsp-config>
<taglib>
<taglib-uri>http://mycompany.com</taglib-uri>
<taglib-location>/WEB-INF/mytag.tld</taglib-location>
</taglib>
</jsp-config>


使用:引入taglib,然后中,pre为标签库,showMsg对应到自定义类,value为自定义类的实例域。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jsp 标签