SimpleTage和SimpleTagSupport是JSP 2.0簡化版的自訂標籤的介面與抽象類別。只需覆寫doTag method,但不像BodyTagSupport可以處理自訂標籤包起來的內容當作JSP解譯,是故在TLD的配置如下:

<taglib xmlns="http://java.sun/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    <tlib-version>1.0</tlib-version>
    <jsp-version>2.0</jsp-version>
    <short-name>Custom Tag</short-name>
    <uri>
http://xyz.com</uri>
    <description>Custom Tag
</description>
    <tag>
        <name>item</name>
        <tag-class>com.foo.ItemTag</tag-class>
        <body-content>empty</body-content> <!—body-content不能為JSP -->
        <attribute>
            <name>itemId</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>   
</taglib>

  接著問題是如何像BodyTagSupport一樣,取得PageContext作為取得Spring的Web Applictation Context的參數呢?如下:

import java.io.IOException;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;

public class ItemTag extends SimpleTagSupport {
    private static Logger logger = LoggerFactory.getLogger(ItemTag.class);
    private static WebApplicationContext _applicationContext;
    private String itemId;
    public void setItemId(String itemId) {  // tld檔的attribute
        this.itemId = itemId;
    }

    private void initApplicationContext(){
        PageContext pageContext = (PageContext) getJspContext(); // 1.強制轉型
        _applicationContext = RequestContextUtils.getWebApplicationContext(
                pageContext.getRequest(),
                pageContext.getServletContext()
        ); // 2.取得Spring的Web Context
    }
    @Override
    public void doTag() throws JspException, IOException {  // 唯一覆寫的method
        if (null == _applicationContext) this.initApplicationContext();
        JspWriter out = this.getJspContext().getOut();          // 3.取得Outputer
        if (this.itemId.equals("1"))
            out.print("disabled");
        logger.debug("doTag OK!!");
    }
}

arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()