SimpleTage和SimpleTagSupport是JSP 2.0簡化版的自訂標籤的介面與抽象類別。只需覆寫doTag method,但不像BodyTagSupport可以處理自訂標籤包起來的內容當作JSP解譯,是故在TLD的配置如下:
接著問題是如何像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!!"); } } |