1. Question: What exactly is tag? How to implement a tag?
A tag is an ordinary Java class, and the only special thing is that it must inherit TagSupport or Bodytagsupport classes. These two classes provide methods that are responsible for the interaction between the JSP page and the class you write, such as input, output. These two classes are provided by the JSP container and need not be implemented by the developer themselves. In other words, you just have to inherit the class that implements the business logic TagSupport or Bodytagsupport, and do some special work, your class is a tag. And it is responsible for the interaction with the JSP page, do not worry about you.
The "special work" usually has the following several steps:
1 provides the property's set method, which can then be set on the JSP page. Take the JSTL tag as an example , this value is the JSP data to the entrance between the tag. So tag must have a SetValue method, the specific properties can not be called value. For example
SetValue (String data) {this.data = data;}
The name of this "value" is defined in the TLD. What name can be taken, just tag to provide the appropriate set method can be.
2) Handling doStartTag or Doendtag. These two methods are provided by TagSupport. Or take as an example, when the JSP parsing this label, in the" "" Trigger the doStartTag event, "" "when the Doendtag event. Typically, logical operations are performed in the doStartTag and the output is controlled in the Doendtag.
3) to write TLD files.
4 in JSP page import TLD
This way, your JSP page will be able to use your own tag.
Usually you will find that most of your activities are concentrated in doStartTag or Doendtag methods. Indeed, it is easy to write taglib after familiarity with some interfaces and classes. As the author of JSP Design says: The logic inside is a little more complicated, but it's not as hard as the rockets.
2, a simple example:OutputTag
package diegoyun;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* @author chenys
*/
public class OutputTag extends TagSupport
{
private String name=null;
public void setName(String name)
{
this.name = name;
}
public int doStartTag() throws JspException{
try
{
JspWriter out = pageContext.getOut();
out.print("Hello! " + name);
}
catch (Exception e)
{
throw new JspException(e);
}
return EVAL_PAGE;
}
}
Brief description:
1, how to output to the JSP page:
Call JspWriter JspWriter out = Pagecontext.getout (), Out.print ...
Just remember this method.