JSP中使用簡單標籤自定義標籤

目錄

簡介

  讓標籤處理器類繼承於SimpleTagSupport類實現自定義標籤功能。
  以下案例的標籤描述默認聲明在 example.tld 中,如:
example.tld

<?xml version="1.0" encoding="UTF-8" ?>
<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>WM103-Example</short-name>
    <uri>/example</uri>

</taglib>

  簡單標籤中繼承SimpleTagSupport類的doTag方法爲空方法,默認不執行標籤體。

使用標籤控制頁面邏輯的案例

開發防盜鏈標籤

RerfererTag.java

package com.wm103.web.example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class RefererTag extends SimpleTagSupport {
    private String site; // 允許訪問的站點
    private String page; // 盜鏈時的跳轉頁面

    public void setSite(String site) {
        this.site = site;
    }

    public void setPage(String page) {
        this.page = page;
    }

    @Override
    public void doTag() throws JspException, IOException {
        PageContext pageContext = (PageContext) this.getJspContext();
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

        String referer = request.getHeader("referer");
        if(referer == null || !referer.startsWith(this.site)) {
            String contextPath = request.getContextPath();
            HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
            if(this.page.startsWith(contextPath)) {
                response.sendRedirect(this.page);
            } else if(this.page.startsWith("/")) {
                response.sendRedirect(contextPath + this.page);
            } else {
                response.sendRedirect(contextPath + "/" + this.page);
            }
        }
    }
}

example.tld

<tag>
    <name>referer</name>
    <tag-class>com.wm103.web.example.RefererTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
        <name>site</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <name>page</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/example" prefix="e"%>
<e:referer site="http://localhost" page="/index.jsp"/>
<html>
<head>
    <title>使用簡單標籤實現防盜鏈</title>
</head>
<body>
    <p>我是防盜的內容!!!</p>
</body>
</html>

開發<c:if>標籤

IfTag.java

package com.wm103.web.example;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class IfTag extends SimpleTagSupport {
    private boolean test;

    public void setTest(boolean test) {
        this.test = test;
    }

    @Override
    public void doTag() throws JspException, IOException {
        if(test) {
            this.getJspBody().invoke(null);
        }
    }
}

example.tld

<tag>
    <name>if</name>
    <tag-class>com.wm103.web.example.IfTag</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
        <name>test</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/example" prefix="e"%>
<html>
<head>
    <title>使用簡單標籤實現if標籤</title>
</head>
<body>
    <%
        session.setAttribute("user", "DreamBoy");
    %>

    <e:if test="${user == null}">
        <p>用戶未登錄!</p>
    </e:if>

    <e:if test="${user != null}">
        <p>用戶已登錄!</p>
    </e:if>

</body>
</html>

開發<c:if><c:else>標籤

3.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/example" prefix="e"%>
<html>
<head>
    <title>使用簡單標籤實現if else標籤</title>
</head>
<body>
    <%
        session.setAttribute("user", "DreamBoy");
    %>

    <e:choose>
        <e:when test="${user == null}">
            <p>用戶未登錄!</p>
        </e:when>
        <e:otherwise>
            <p>用戶已登錄!</p>
        </e:otherwise>
    </e:choose>
</body>
</html>

ChooseTag.java

package com.wm103.web.example;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class ChooseTag extends SimpleTagSupport {
    private boolean isDo;

    public boolean isDo() {
        return isDo;
    }

    public void setDo(boolean aDo) {
        isDo = aDo;
    }

    @Override
    public void doTag() throws JspException, IOException {
        this.getJspBody().invoke(null);
    }
}

WhenTag.java

package com.wm103.web.example;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class WhenTag extends SimpleTagSupport {
    private boolean test;

    public void setTest(boolean test) {
        this.test = test;
    }

    @Override
    public void doTag() throws JspException, IOException {
        ChooseTag parent = (ChooseTag) this.getParent();
        if(test && !parent.isDo()) {
            this.getJspBody().invoke(null);
            parent.setDo(true);
        }
    }
}

OtherwiseTag.java

package com.wm103.web.example;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class OtherwiseTag extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        ChooseTag parent = (ChooseTag) this.getParent();
        if(!parent.isDo()) {
            this.getJspBody().invoke(null);
            parent.setDo(true);
        }
    }
}

example.tld

<tag>
    <name>choose</name>
    <tag-class>com.wm103.web.example.ChooseTag</tag-class>
    <body-content>scriptless</body-content>
</tag>
<tag>
    <name>when</name>
    <tag-class>com.wm103.web.example.WhenTag</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
        <name>test</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>
<tag>
    <name>otherwise</name>
    <tag-class>com.wm103.web.example.OtherwiseTag</tag-class>
    <body-content>scriptless</body-content>
</tag>

開發<c:forEach>標籤

ForEachTag.java

package com.wm103.web.example;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class ForEachTag extends SimpleTagSupport {
    Object items;
    String var;

    public void setVar(String var) {
        this.var = var;
    }

    /*public void setItems(Object items) {
        this.items = items;
    }*/

    /*@Override
    public void doTag() throws JspException, IOException {
        List list = (List) items;
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Object value = it.next();
            this.getJspContext().setAttribute(this.var, value);
            this.getJspBody().invoke(null);
        }
    }*/

    private Collection collection;

    public void setItems(Object items) {
        this.items = items;
        this.collection = new ArrayList<>();
        if(items instanceof Collection) {
            this.collection = (Collection) items;
        } else if(items instanceof Map) {
            Map map = (Map) items;
            this.collection = map.entrySet();
        } else if(items.getClass().isArray()) {
            int length = Array.getLength(items);
            for(int i = 0; i < length; i++) {
                this.collection.add(Array.get(items, i));
            }
        }
    }

    @Override
    public void doTag() throws JspException, IOException {
        Iterator it = this.collection.iterator();
        while (it.hasNext()) {
            Object value = it.next();
            this.getJspContext().setAttribute(this.var, value);
            this.getJspBody().invoke(null);
        }
    }
}

example.tld

<tag>
    <name>forEach</name>
    <tag-class>com.wm103.web.example.ForEachTag</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
        <name>var</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
        <name>items</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

4.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>
<%@ taglib uri="/example" prefix="e"%>
<html>
<head>
    <title>使用簡單標籤實現forEach標籤</title>
</head>
<body>
    <%
        List list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        request.setAttribute("list", list);
    %>

    <e:forEach var="value" items="${list}">
        <p>${value}</p>
    </e:forEach>

    <%
        Map map = new HashMap();
        map.put("aaa", "a1");
        map.put("bbb", "b1");
        map.put("ccc", "c1");
        map.put("ddd", "d1");
        request.setAttribute("map", map);
    %>

    <e:forEach var="entry" items="${map}">
        <p>${entry.key} -- ${entry.value}</p>
    </e:forEach>

    <%
        int[] array = {1, 2, 3, 4};
        request.setAttribute("array", array);
    %>

    <e:forEach var="value" items="${array}">
        <p>${value}</p>
    </e:forEach>
</body>
</html>

使用簡單標籤實現html轉移標籤

HtmlFilter.java

package com.wm103.web.example;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.io.StringWriter;

public class HtmlFilterTag extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        StringWriter writer = new StringWriter();
        JspFragment jf = this.getJspBody();
        jf.invoke(writer);
        String content = writer.getBuffer().toString();
        content = filter(content); // 進行轉義
        this.getJspContext().getOut().write(content);
    }

    public String filter(String message) {

        if (message == null)
            return (null);

        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuilder result = new StringBuilder(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
                case '<':
                    result.append("&lt;");
                    break;
                case '>':
                    result.append("&gt;");
                    break;
                case '&':
                    result.append("&amp;");
                    break;
                case '"':
                    result.append("&quot;");
                    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());

    }
}

example.tld

<tag>
    <name>htmlFilter</name>
    <tag-class>com.wm103.web.example.HtmlFilterTag</tag-class>
    <body-content>scriptless</body-content>
</tag>

5.jsp

<e:htmlFilter>
    <a href="">點擊鏈接</a>
</e:htmlFilter>

打包標籤庫

  • 創建Java工程,並把標籤處理類複製到工程中;
  • 在Java工程中創建META-INF目錄,並將標籤庫描述文件放置在該目錄下;
  • 將Java工程導出爲jar包;
  • 在Java Web工程中引入該jar包即可使用jar包中定義的標籤。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章