taglib例子

jsp中的taglib有点类似asp.net中的customer control。自定义标签。

一个最简单的taglib使用例子:检查用户是否已经被登陆。

新建一个class: CheckLoginTag

package com.my.taglib;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;

public class CheckLoginTag extends TagSupport {
    private String role;
    public String getRole() {
        return this.role;
    }
    public void setRole(String role) {
        this.role = role;
    }

    public CheckLoginTag() {}
    
    public int doEndTag() {
        try {
            System.out.println(role);
            String user = (String)pageContext.getSession().getAttribute("USER");
            if(user == null || user.equals("")) {
                HttpServletResponse response = (HttpServletResponse)pageContext.getResponse();
                response.sendRedirect("/mytest/login");
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}

 

在WEB-INF目录下建一个tag目录,新建一个文件:checking.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>checking</short-name>
    <uri>/taglibs/checking</uri>
    <tag>
        <description>Check Login</description>
        <name>login</name>
        <tag-class>com.my.taglib.CheckLoginTag</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>role</name>
            <required>true</required>
        </attribute>
    </tag>
</taglib>

 

打开web.xml,加入内容到<web-app/>内:

    <jsp-config>
        <taglib>
            <taglib-uri>/WEB-INF/tags/checking.tld</taglib-uri>
            <taglib-location>/WEB-INF/tags/checking.tld</taglib-location>
        </taglib>
    </jsp-config>

 

新建一个JSP: testtag.jsp

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>

<%@ taglib prefix="checking" uri="/WEB-INF/tags/checking.tld" %>

<html>
    <header>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </header>
    <body>
        <checking:login role="admin" />
    </body>
</html>


运行结果:如果用户未登陆将会跳转到login.jsp。

你可能感兴趣的:(taglib)