Recipe 22.6 Using the Custom Tag in a JSP


Problem

You want to use a custom tag that you have developed and installed.

Solution

Include a taglib directive at the top of the JSP. The taglib directive must identify the uri for your tag library, as that uri is specified in your TLD file.

Discussion

To use the custom tags from your tag library, the JSP has to have a taglib directive, as in Example 22-4. The uri attribute matches the uri your TLD file specifies (see Recipe 22.5). The prefix attribute specifies the namespace for your tags. Example 22-4 specifies the prefix cbck ; therefore, the JSP uses the logo tag from that tag library in the manner of <cbck:logo>...</cbck:logo> .

If the tag encloses body content (it's not an empty tag), make sure to close the tag properly, as in </cbck:logo> as opposed to </logo> .


If the JSP does not use the tag as specified in the TLD (for example, if it leaves out a mandatory attribute), the JSP will fail to compile the first time it is requested .

Example 22-4. The Logo tag used in a JSP
  <%@ taglib uri="jspservletcookbook.com.tags" prefix="cbck" %>  <html> <head><title>Mi casa es su casa</title></head> <body>  <cbck:logo heading="<%=request.getParameter("level") %>" image="stamp.gif" width="42"  height="54">Thanks for visiting</cbck:logo>  Here's all the other stuff this page contains... </body> </html> 

In Example 22-4, the logo tag's heading attribute takes a runtime expression value so that the user can dynamically set the attribute value, as in the following URL: http://localhost:8080/home/logoTest.jsp?level=1 .

Figure 22-2 shows the web browser display for this JSP.

Figure 22-2. The web browser display of a custom tag output
figs/jsjc_2202.gif

See Also

The JSP 2.0 specification web page: http://jcp.org/en/jsr/detail?id=152; Recipe 22.2 and Recipe 22.3 on creating TLD files for tag libraries; Recipe 22.4 and Recipe 22.5 on packaging a tag library in a web application; Recipe 22.7 on handling exceptions in tags; Recipe 22.8 and Recipe 22.9 on creating a simple tag handler; Recipe 22.10 on using the simple tag handler in a JSP; Recipe 22.11-Recipe 22.14 on using a JSP tag file ; Recipe 22.15 on adding a listener class to a tag library; the custom tag sections of Hans Bergsten's JavaServer Pages , Third Edition (O'Reilly).



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net