Java Web custom tag library

We use Struts and JSTL when exposed to tag library

That is some.Tld suffix documents.
When we introduce these files, you can use tags to complete the development of a variety of web layer.
Here is the saints javaweb45 custom tag library content to do a note.

The Java class we need some one label first, MyTag.java.
This class inherits from TagSupport, the parent of API can be found in the JavaEE API.
Rewrite the MyTag two parent class method, respectively (doStartTag) and doEngTag()

package com.lj.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

public class MyTag extends TagSupport
{
	@Override
	public int doStartTag() throws JspException
	{
		try
		{
			this.pageContext.getOut().println("hello world");
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return EVAL_BODY_INCLUDE;
		
	}
	
	
	@Override
	public int doEndTag() throws JspException
	{
		try
		{
			this.pageContext.getOut().println("welcome");
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return EVAL_PAGE;
	}
}




Then to write a TLD file, the file is used to define all of the tag.
This file should be placed below the WEB-INF here.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	version="2.0"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
	
	  
	
	<tlib-version>1.0</tlib-version>
	<short-name>myTag</short-name>
	
        <!--uri defines a reference path for this label,  <%@taglib uri='/myTag'%>-->
	<uri>/myTag</uri>
	
	
	<tag>
		<name>firstTag</name>
		<tag-class>com.lj.tag.MyTag</tag-class>
		<body-content>empty</body-content>
		
	</tag>
	
	</taglib>




At the end of the file is JSP, a new tag1.jsp

We introduce the definition of JSP in the TLD file, you can use tags defined in TLD.

<%@taglib prefix="hello" uri="/myTag" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'tag1.jsp' starting page</title>
    
	 
  </head>
  
  <body>
     <hello:firstTag/>
     
     
  </body>
</html>




The final results:
hello world welcome

Posted by Hunk at November 29, 2013 - 6:18 AM