天天看点

JSP中自定义标记库的使用(三)

 三、一个简单的范例 

1、创建hello标签:定义一个名为mytaglib的标签库,它包含一个简单的hello标签,这个标签能够将 

JSP页面中所有的解析为字符串"hello". 

A、hello标签的处理类: 

代码 

public int doEndTag() throws JspException{ 

             try{ 

                      pageContext.getOut().print("hello"); 

                  }catch(Exception e){ 

                      throw new JspTagException(e.getMessage()); 

                  }                  return EVAL_PAGE;      }   

B、创建标签库描述文件:.tld文件存放位置;标签库名,标签名,属性,对应的处理类。 

C、web.xml中引入标签库: 

代码 

... ... 

             /mytaglib 

            /WEB-INF/tld/mytaglib.tld 

... ...   

D、JSP页面中引入标签库说明,并使用标签: 

taglib指令中,prefix属性值用作指代mytaglib标签库。 

四、另一个标签 

1、创建一个能替换helloapp应用中JSP网页的静态文本的标签,这个标签名为message,它放在mytaglib标签库中。 

2、在hellowithtag2.jsp文件中使用message标签的代码如下: 

当客户访问hello.jsp网页时,message标签的处理类会根据属性key的值从一个文本文件中找到与key匹配的字符串。假定这个字符串为“Hello”,然后将这个字符串输出到网页上。 

3、创建包含JSP网页静太文本的文件 

messageresource.properties: 

hello.title=Title of hello.jsp 

hello.hello=hello 

4、 

代码 

由<span style="color:red;">DispatcherServlet</span>类的init方法负责从静态文本中读取静态文本,然后把它们装载到Properties对象中,最后再把这个Properties对象作为属性保存到ServletContext中。   

5、DispatcherServlet类的init方法: 

代码 

public void init(ServletConfig config) throws ServletException{ 

           super.init(config); 

           Properties ps=news Properties(); 

           SevletContext c.getServletContext(); 

           InputStream in=context.getResourceAsStream("/WEB-INF/messageresource"); 

           ps.load(in); 

           in.close(); 

            context.setAttribute("ps",ps); 

     }   

6、为保证在WEB应用启动时就加载DispathcherServlet,应该在web.xml中配置这个Servlet时的设置load-on-startup属性: 

dispacher 

mypack.DspacherServlet 

n dispatcher n mypack.DispatcherServlet n 1 7、创建MessageTag标签处理类 

MessageTag包含一个成员变量key ,它与message标签的属性key 对应,在MessageTag 

中定义了getKey和setKey 方法。 

代码 

   private String key=null; 

       public String getKey(){ 

              return this.key; 

      } 

        public void setKey(String key) 

              this.key=key; 

    } 

  在MessageTag的doEndTag方法中,首先从pageContext中读取包含静态文本的Properties对象: 

代码 

Properties ps=(Properties)pageContext.getAttribute("ps",pageContext.APPLACTION_SCOPE);  然后从Properties对象中读取key对应的静态文本,最后输出该文本: 

代码 

String message=null; 

  message=(String)ps.get(key); 

  pageContext.getOut.print(message); 

  8、mytaglib库中定义message标签: 

代码 

message 

     mypack.MessageTag 

    empty 

     produce message by key 

           key 

      true   

后记: 

1问题:在标签处理类中,如何访问session范围内的共享数据? 

选项: 

(B)在标签处理类TagSupport类中定义了pageContext成员变量,先通过它的 

getSession()方法获得当前的HttpSession对象,再调用HttpSession对 

象的getAttribute()方法。