自定义JSP标记标签自定义JSP函数

自定义JSP标记标签自定义JSP函数

一、获取 .tld 文件头
1、文件头路径: Tomcat\webapps\examples\WEB-INF\jsp2\jsp2-example-taglib.tld
2、.tld文件存放位置: project/webapp/WEB-INF/ (必须放在WEB-INF 目录下面)

二、实现自定义函数
1、 编辑 .tld文件:
  <description>自定义函数,用于在jsp页面使用 </description>
  <tlib-version>1.0</tlib-version>
  <jspversion>1.0</jspversion>
  <short-name>fns</short-name>
    
<function>
  		<description>获取当前时间 yyyy-MM-dd</description>
  		<name>nowDate</name>
  		<function-class>com.xx.study.utils.DateUtils</function-class>
  		<function-signature>java.lang.String nowDate()</function-signature>
  		<example>${fns:nowDate()}</example>
  	</function>




2、DateUtils.java (注意: 方法必须是静态的
/**
	 * @description: 获取当前时间 yyyy-MM-dd 格式
	 * @return
	 */
	public static String nowDate(){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date());
	}


3、JSP页面使用
  • 导入标记: <%@ taglib uri="/WEB-INF/tlds/fns.tld" prefix="fns" %>
  • 获取时间: <h3>当前时间是: ${fns:nowDate()}</h3>

三、实现自定义标记
1、编辑 nowTag.tld 文件
<description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>nowTag</short-name>
    <tag>
        <description>this tag get now time</description>
        <name>time</name>
        <tag-class>com.xx.study.tag.TimerTag</tag-class>
        <body-content>empty</body-content>
    </tag>


2、TimerTag.java (注意: 必须继承 TagSupport
public class TimerTag extends javax.servlet.jsp.tagext.TagSupport{
	@Override
	public int doStartTag() throws JspException {
		return EVAL_BODY_INCLUDE;
	}
	
	@Override
	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.print(DateUtils.nowDate());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}
}



3、JSP页面使用
  • 导入标记: <%@ taglib uri="/WEB-INF/tlds/nowTag.tld" prefix="nowTag"%>
  • 获取时间: <h2>当前时间:<nowTag:time/> </h2>




参考资料: JSP 自定义函数


猜你喜欢

转载自blog.csdn.net/haha_sir/article/details/80557597