jsp自定义标签

来源:互联网 发布:手机理财软件哪个好 编辑:程序博客网 时间:2024/05/22 12:36

实际开发时,不能出现大量的html+java代码相混合的jsp页面


为了方便,可以将业务逻辑封装到符合jsp规范的类或者接口中,然后自己定义标签满足不同的需求。


举例:在页面中显示当前的时间,格式为:年,月,日------时,分,秒


jsp脚本开发:<%SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");String date = sdf.format(new Date());%>

当前时间为:<%=date %>

显示结果:。。。。。。(你运行时的当前时间)

first:编写自定义标签的业务逻辑处理类


源码中的导包就不写了,懒!

public class DateTag extends TagSupport{

public int doStartTag() throws JspException{

//编写业务逻辑

SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

String date = sdf.format(new Date());

try{

//输出结果

pageContext.getOut().print(date);

}catch(IOException e){

e.printStackTrace();

}

return super.doStartTag();

}

}

second:在WEB-INF目录下编写*。tld文件注册标签,.tld文件格式可以参考Tomcat安装目录下的文件


coby下模板,以后可能用的上

<?xmlversion="1.0"encoding="UTF-8"?>

<taglibxmlns="http://java.sun.com/xml/ns/j2ee"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"

   version="2.0">

    <description>A tag library exercising SimpleTag handlers.</description>

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

    <short-name>SimpleTagLibrary</short-name>

    <uri>/oracle-tag</uri>

    <tag>

        <name>date</name>

        <tag-class>com.tag.date.DateTag</tag-class>

        <body-content>empty</body-content>

    </tag>

</taglib>

third:在jsp页面导入自定义标签库,并使用自定义标签

。。。。。

<html>

<body>

当期时间为:<o:date/>

</body>

</html>


运行后结果同上。