Example of simple tag with dynamic row data: iterating the body
Here are all the code for demonstrating how to use a simple tag with dynamic row data.
1. TLD file "test.tld" under WEB-INF directory. I saw many people asking how to make TLD file online, you just create a file named .tld, that's all. Eclipse doesn't provide IDE tools to help.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>testing</short-name> <uri>simpleTags</uri> <description>This is a demonstration tag library</description> <tag> <name>simple4</name> <tag-class>com.programcreek.test.SimpleTagTest</tag-class> <body-content>scriptless</body-content> </tag> </taglib> |
2. A JSP page "result.jsp"
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="myTags" uri="simpleTags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Testing Custom Tag</title> </head> <body> <table border="1"> <myTags:simple4> <tr> <td> ${movie} </td> </tr> </myTags:simple4> </table> </body> </html> |
3. Tag handler class "SimpleTagTest"
package com.programcreek.test; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class SimpleTagTest extends SimpleTagSupport { String[] movies = {"monsoon Wedding", "Saved", "Fahrenheit 9/11"}; public void doTag() throws JspException, IOException{ for(int i = 0; i < movies.length; i++){ getJspContext().setAttribute("movie", movies[i]); getJspBody().invoke(null); } } } |
<pre><code> String foo = "bar"; </code></pre>