JSP Custom Tag Working Example

To write your own jsp tag:
Create a HelloTag class that extends SimpleTagSupport class.
Example:
  1. import javax.servlet.jsp.tagext.*;
  2. import javax.servlet.jsp.*;
  3. import java.io.*;
  4. public class HelloTag extends SimpleTagSupport {
  5. private String message;
  6. public void setMessage(String msg) {
  7. this.message = msg;
  8. }
  9. StringWriter sw = new StringWriter();
  10. public void doTag()
  11. throws JspException, IOException
  12. {
  13. if (message != null) {
  14. /* Use message from attribute */
  15. JspWriter out = getJspContext().getOut();
  16. out.println( message );
  17. }
  18. else {
  19.      System.out.println("msg is null");
  20. /* use message from the body */
  21. getJspBody().invoke(sw);
  22. getJspContext().getOut().println(sw.toString());
  23. }
  24. }
  25. }
Now create a  custom .tld file:
custom.tld:
-----------
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
  3. <taglib>
  4. <tlib-version>1.0</tlib-version>
  5. <jsp-version>2.0</jsp-version>
  6. <short-name>Example TLD with Body</short-name>
  7. <tag>
  8. <name>Hello</name>
  9. <tag-class>com.mohi.HelloTag</tag-class>
  10. <body-content>scriptless</body-content>
  11. <attribute>
  12. <name>message</name>
  13. </attribute>
  14. </tag>
  15. </taglib>
Usage:
Put the definitio on the top of your jsp page:
  1. <%@ taglib prefix="ex" uri="../custom.tld"%>//be aware of the path you are using it's relative!
Using your tag in jsp page body:
  1. <ex:Hello message="This is custom tag" />

Sample code:
Download JSPCustomTagExamplecode.zip
Unzip and run:
mvn clean install tomcat7:run
Browse to http://localhost:8080/SpringMVC/welcome

No comments:

Post a Comment