JSP/Servlet基础——自定义标签库

来源:互联网 发布:前海开源人工智能基金 编辑:程序博客网 时间:2024/05/21 08:00

笔记,只供自己参考。水平相当初级。

1 写一个标签类,继承SimpleTagSupport,如果是动态属性,还要实现DynamicAttributes接口

package practice.tag;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;/** * 继承SimpleTagSupport类 */public class HelloTag extends SimpleTagSupport{@Overridepublic void doTag()throws JspException, IOException{getJspContext().getOut().write("Hello World " + new java.util.Date());}}

2 写tld文件。
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"version="2.0"><!-- 版本必须填写 --><tlib-version>1.0</tlib-version><short-name>mytaglib</short-name><uri>http://www.tom.com/mytaglib</uri><tag><name>hello</name><tag-class>practice.tag.HelloTag</tag-class><body-content>empty</body-content></tag></taglib>

3 在web.xml中引入标签库
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><display-name>practice.tag</display-name><!-- 配置标签库 --><jsp-config><taglib><taglib-uri>/mytaglib</taglib-uri><taglib-location>/WEB-INF/tld/mytaglib.tld</taglib-location></taglib></jsp-config><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>

4 在jsp文件中通过编译指令引入标签库,使用自定义标签
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!-- 引入 --><%@ taglib uri="http://www.tom.com/mytaglib" prefix="t"%><title>Insert title here</title></head><body><!-- 使用 --><t:hello /></body></html>

tips:
1 修改jsp文件的默认编码


2 修改web工程发布在Tomcat中的上下文根


标签分几种
1 没有标签体,没有属性
2 有属性
3 有标签体
4 以页面片段作为属性的标签
5 动态属性的标签

(1)HelloWorldTag 
package tag;

import java.io.IOException;

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

public class HelloWorldTag extends SimpleTagSupport
{
public void doTag() throws JspException, IOException
{
getJspContext().getOut().write("Hello World " + new java.util.Date());
}
} 

(2) QueryTag
package tag;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class QueryTag extends SimpleTagSupport
{
    // 标签属性
    private String driver;
    private String url;
    private String user;
    private String pass;
    private String sql;
    public String getDriver()
    {
        return driver;
    }
    public void setDriver(String driver)
    {
        this.driver = driver;
    }
    public String getUrl()
    {
        return url;
    }
    public void setUrl(String url)
    {
        this.url = url;
    }
    public String getUser()
    {
        return user;
    }
    public void setUser(String user)
    {
        this.user = user;
    }
    public String getPass()
    {
        return pass;
    }
    public void setPass(String pass)
    {
        this.pass = pass;
    }
    public String getSql()
    {
        return sql;
    }
    public void setSql(String sql)
    {
        this.sql = sql;
    }
    // 执行数据库访问的对象
    private Connection conn = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    private ResultSetMetaData rsmd = null;
    public void doTag() throws JspException, IOException
    {
        try
        {
            Class.forName(driver);
            conn = DriverManager.getConnection(urluserpass);
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            Writer out = getJspContext().getOut();
            out.write("<table border='1' bgColor='#9999cc' width='400'>");
            while (rs.next())
            {
                out.write("<tr>");
                for (int i = 1; i <= columnCount; i++)
                {
                    out.write("<td>");
                    out.write(rs.getString(i));
                    out.write("</td>");
                }
                out.write("</tr>");
            }
            out.write("</table>");
        } catch (ClassNotFoundException cnfe)
        {
            cnfe.printStackTrace();
            throw new JspException("自定义标签错误" + cnfe.getMessage());
        } catch (SQLException ex)
        {
            ex.printStackTrace();
            throw new JspException("自定义标签错误" + ex.getMessage());
        } finally
        {
            try
            {
                if (rs != null)
                {
                    rs.close();
                }
                if (stmt != null)
                {
                    stmt.close();
                }
                if (conn != null)
                {
                    conn.close();
                }
            } catch (SQLException sqle)
            {
                sqle.printStackTrace();
            }
        }
    }
}

(3)有标签体的标签
package tag;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class IteratorTag extends SimpleTagSupport
{
    private String collection;
    private String item;
    public String getCollection()
    {
        return collection;
    }
    public void setCollection(String collection)
    {
        this.collection = collection;
    }
    public String getItem()
    {
        return item;
    }
    public void setItem(String item)
    {
        this.item = item;
    }
    public void doTag() throws JspException, IOException
    {
        Collection itemList = (Collection) getJspContext().getAttribute(
                collection);
        for (Object s : itemList)
        {
            getJspContext().setAttribute(item, s);
            getJspBody().invoke(null);
        }
    }
}

(4)以页面片段作为属性的标签 
package tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class FragmentTag extends SimpleTagSupport
{
    private JspFragment fragment;
    public JspFragment getFragment()
    {
        return fragment;
    }
    public void setFragment(JspFragment fragment)
    {
        this.fragment = fragment;
    }
    public void doTag() throws JspException, IOException
    {
        JspWriter out = getJspContext().getOut();
        out.println("<div style='padding:10px;border:1px solid black'>");
        out.println("<h3>下面是动态传入的JSP片段</h3>");
        fragment.invoke(null);
        out.println("</div>");
    }
}

(5)动态属性标签
package tag;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.DynamicAttributes;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class DynamicAttributesTag extends SimpleTagSupport implements
DynamicAttributes
{
private ArrayList<String> keys = new ArrayList<String>();
private ArrayList<Object> values = new ArrayList<Object>();

@Override
public void doTag() throws JspException, IOException
{
JspWriter out = getJspContext().getOut();
out.println("<ol>");
for (int i = 0; i < keys.size(); i++)
{
String key = keys.get(i);
Object value = values.get(i);
out.println("<li>" + key + "=" + value + "</li>");
}
out.println("</ol>");
}

@Override
public void setDynamicAttribute(String uri, String localName, Object value)
throws JspException
{
// TODO Auto-generated method stub
keys.add(localName);
values.add(value);
}

}


(6)tld文件 // 放到web-inf的jsp2目录下
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor 
    license agreements. See the NOTICE file distributed with this work for additional 
    information regarding copyright ownership. The ASF licenses this file to 
    You under the Apache License, Version 2.0 (the "License"); you may not use 
    this file except in compliance with the License. You may obtain a copy of 
    the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required 
    by applicable law or agreed to in writing, software distributed under the 
    License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 
    OF ANY KIND, either express or implied. See the License for the specific 
    language governing permissions and limitations under the License. -->
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://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>mytaglib</short-name>
    <uri>http://www.tom.com/mytaglib</uri>
    <tag>
        <description>Outputs Hello, World</description>
        <name>helloWorld</name>
        <tag-class>tag.HelloWorldTag</tag-class>
        <body-content>empty</body-content>
    </tag>
    <tag>
        <name>query</name>
        <tag-class>tag.QueryTag</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>driver</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
        <attribute>
            <name>driver</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
        <attribute>
            <name>url</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
        <attribute>
            <name>user</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
        <attribute>
            <name>pass</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
        <attribute>
            <name>sql</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
    </tag>
    <tag>
        <name>iterator</name>
        <tag-class>tag.IteratorTag</tag-class>
        <body-content>scriptless</body-content> //表示不能有JSP脚本,只能有静态html元素和EL
        <attribute>
            <name>collection</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
        <attribute>
            <name>item</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
    </tag>
    <tag>
        <name>frag</name>
        <tag-class>tag.FragmentTag</tag-class>
        <body-content>empty</body-content> // 这个地方是empty
        <attribute>
            <name>fragment</name>
            <required>true</required>
            <fragment>true</fragment>
        </attribute>
    </tag>
    <tag>
        <name>dynaAttr</name>
        <tag-class>tag.DynamicAttributesTag</tag-class>
        <body-content>empty</body-content>
        <dynamic-attributes>true</dynamic-attributes>
    </tag>
</taglib>


(7)使用标签的页面 welcome.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ page import="java.util.*"%>
<%@ taglib uri="http://www.tom.com/mytaglib" prefix="tom"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>欢迎</title>
<link rel="stylesheet" href="onlyone.css" type="text/css" />
</head>
<body>
    <div id="content">
        勇士,你要去哪?<br />
        <div class="tagDemo">
            helloWorld标签<br />
            <tom:helloWorld />
        </div>
        <div class="tagDemo">
            带属性的标签
            <tom:query driver="oracle.jdbc.driver.OracleDriver"
                url="jdbc:oracle:thin:localhost:1521:orcl" user="system"
                pass="abc123" sql="select * from vampireDiaries" />
        </div>
        <div class="tagDemo">
            带标签体的标签
            <%
            List<String> a = new ArrayList<String>();
            a.add("Demo");
            a.add("Katherine");
            pageContext.setAttribute("a", a);
        %>
            <table>
                <tom:iterator collection="a" item="tmp">
                    <tr>
                        <td>${pageScope.tmp}</td>
                    </tr>
                </tom:iterator>
            </table>
        </div>
        <div class="tagDemo">
            以页面片段作为属性的标签
            <tom:frag>
                <jsp:attribute name="fragment">
            <tom:helloWorld />
           </jsp:attribute>
            </tom:frag>
            <br />
            <tom:frag>
                <jsp:attribute name="fragment">
            ${pageContext.request.remoteAddr }
           </jsp:attribute>
            </tom:frag>
        </div>
        <div class="tagDemo">
            动态属性的标签:属性的数量可以随意变化
            <h4>指定两个属性</h4>
            <tom:dynaAttr name="human" 智商="90" />
            <h4>指定三个属性</h4>
            <tom:dynaAttr a="1" b="2" c="3" />
        </div>
    </div>
</body>
</html>

(8)onlyone.css
@CHARSET "UTF-8";
/* 主要的模块 */
#content {
    margin: auto;
    width: 900px;
    font-size: 2em;
    font-style: italic;
    font-weight: boldcolor : #990000font-family : "Times New Roman",
    Georgia, Serif;
    background-color: #339933;
    font-family: "Times New Roman", Georgia, Serif;
    color: #990000;
}
.tagDemo {
    border: 3px solid red;
    width: 500pxfloat : left;
    overflow: hidden;
    float: left;
}



0 0
原创粉丝点击