Create a HelloTag class that extends SimpleTagSupport class.
Example:
- import javax.servlet.jsp.tagext.*;
- import javax.servlet.jsp.*;
- import java.io.*;
- public class HelloTag extends SimpleTagSupport {
- private String message;
- public void setMessage(String msg) {
- this.message = msg;
- }
- StringWriter sw = new StringWriter();
- public void doTag()
- throws JspException, IOException
- {
- if (message != null) {
- /* Use message from attribute */
- JspWriter out = getJspContext().getOut();
- out.println( message );
- }
- else {
- System.out.println("msg is null");
- /* use message from the body */
- getJspBody().invoke(sw);
- getJspContext().getOut().println(sw.toString());
- }
- }
- }
custom.tld:
-----------
- <?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>Example TLD with Body</short-name>
- <tag>
- <name>Hello</name>
- <tag-class>com.mohi.HelloTag</tag-class>
- <body-content>scriptless</body-content>
- <attribute>
- <name>message</name>
- </attribute>
- </tag>
- </taglib>
Usage:
Put the definitio on the top of your jsp page:
- <%@ taglib prefix="ex" uri="../custom.tld"%>//be aware of the path you are using it's relative!
Using your tag in jsp page body:
- <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
Unzip and run:
mvn clean install tomcat7:run
Browse to http://localhost:8080/SpringMVC/welcome
No comments:
Post a Comment