JSP模板应用指南(下)

2019-05-27 21:40:19于丽

  import javax.servlet.jsp.tagext.TagSupport;

  import beans.templates.PageParameter;

  public class GettagextendstagSupport {

   private String name;

   // setter method for name attribute

   public void setName(String name) {

     this.name = name;

   }

   public int doStartTag() throws JspException {

     // obtain reference totemplate stack

     Stack stack = (Stack)pageContext.get attribute (

         "template-stack", PageContext.REQUEST_SCOPE);

     // stack should not be null

     if(stack == null)

       throw new JspException("GetTag.doStartTag(): " +

                   "NO STACK");

     // peek at hashtable

     Hashtable params = (Hashtable)stack.peek();

     // hashtable should not be null

     if(params == null)

       throw new JspException("GetTag.doStartTag(): " +

                   "NO HASHTABLE");

     // get page parameter from hashtable

     PageParameter param = (PageParameter)params.get(name);

     if(param != null) {

       String content = param.getContent();

       if(param.isDirect()) {

        // print content if direct attribute is true

        try {

         pageContext.getOut().print(content);

        }

        catch(java.io.IOException ex) {

         throw new JspException(ex.getMessage());

        }

       }

       else {

        // include content if direct attribute is false

        try {

         pageContext.getOut().flush();

         pageContext.include(content);

        }

        catch(Exception ex) {

         throw new JspException(ex.getMessage());

        }

       }

     }

     return SKIP_BODY; // not interested in tagbody, if present

   }

   // taghandlers should always implement release() because

   // handlers can be reused by the JSP container

   public void release() {

     name = null;

   }

  }

  GetTag.doStartTag从请求区域返回了页面参数bean并从bean中获得了content和direct 属性。然后,内容可以根据direct属性值选择是被包含还是显示。

结论
  模板是一种简单而有非常有用的概念。模板的封装布局能够对布局改变的影响达到最小化。而且模板能够根据用户的不同来区分不同的内容,它还能够嵌套到其他的模板和JSP页面中。