JSP可以使用标签 **自定义函数
1.自己描述一个类
2.类中描述自己的方法
方法必须是静态的且通常有返回值(没有返回值无法展示没有意义)
3.配置一个说明书—-xxx.tld
当前工程下web文件夹中WEB-INF文件夹下创建一个新的xxx.tld文件
uri、short-name、很重要
**
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>myFn</short-name>
<uri>http://http://www.duyiedu.com</uri>
<!-- Invoke 'Generate' action to add tags or functions -->
<function>
<name>add</name>
<function-class>myfn.MyFunctions</function-class>
<function-signature>int add(int,int)</function-signature>
</function>
</taglib>
4.在JSP中声明头信息(我们自己设置的)
运行结果
JSP可以使用标签 **自定义标签
1.每一个标签都是一个单独的类,创建一个类实现Tag接口,重写里面的方法
2.细致的看一下这些方法
两组对应的get/set方法,按需求自己补全,并添加相应的私有属性
还有一个单独的release方法,回收对象
doStartTag
doEndTag
3.在后面两个方法内添加自己的逻辑**
package mytag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import java.io.IOException;
public class MyOut implements Tag{
private PageContext pageContext;
@Override
public void setPageContext(PageContext pageContext) {
this.pageContext=pageContext;
}
public PageContext getPageContext() {
return pageContext;
}
private Tag parent;
@Override
public void setParent(Tag tag) {
this.parent=tag;
}
@Override
public Tag getParent() {
return this.parent;
}
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public int doStartTag() throws JspException {
return Tag.EVAL_BODY_INCLUDE;
}
@Override
public int doEndTag() throws JspException {
JspWriter out=this.pageContext.getOut();
try {
out.write(value+" is cute !");
} catch (IOException ioException) {
ioException.printStackTrace();
}
return Tag.EVAL_PAGE;
}
@Override
public void release() {
}
}
4.描述一个说明书 tld
先描述uri和short-name,再描述标签及标签内部的属性
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>myTag</short-name>
<uri>http://www.duyiedu.com</uri>
<!-- Invoke 'Generate' action to add tags or functions -->
<tag>
<name>out</name>
<tag-class>mytag.MyOut</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>value</name>
<!-- 属性是否必须有-->
<required>true</required>
<!-- 是否支持EL表达式-->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
5.声明头信息
运行结果