自定义JSP标签01

第三章我们遇见了一个JSP标签,为了让接下来的学习能更清晰地认识标签,故做了以下hello.jsp中的hello标签与web.xml标签中的<taglib>元素,mytaglib.tld文件中的<tag>元素,以及HelloTag.class文件之前的对应关系

12.1认识JSP标签

标签编程在实际工作的开发中并不是很常见,也就是说自己开发标签的情况基本上是不存在的。因为这个与开发环境所限制,自己开发后的标签没有通用性。所有在实际中都是大量使用以及开发号的标签。例如JSTL或者Struts中都有标签。在这里学习自定义标签是为了建立一个完整的知识体系,更好的学习后边的内容。

在JSP开发中就是在HTML代码中嵌入了大量的Java代码,这样一来使JSP页面充满了Java程序,维护起来非常不方便,那么此时就可以通过标签来完成。

如果用户想要定义一个标签的话,直接继承TagSupport类

定义标签支持类:HelloTag.java

package org.lxh.tagdemo ;
import javax.servlet.jsp.* ;
import javax.servlet.jsp.tagext.* ;
public class HelloTag extends TagSupport{
    public int doStartTag() throws JspException{
        JspWriter out = super.pageContext.getOut() ;
        try{
            out.println("<h1>Hello World!!!</h1>") ;
        }catch(Exception e){}
        return TagSupport.SKIP_BODY ;
    }
}

在标签开发之中最麻烦的就是返回值,下面给出一个返回值,由于现在定义的是一个没有标签体的标签,所有该返回值表示标签的其他内容不再执行。(导入jsp-api.jar包)

只靠一个标签的支持类是无法完成全部功能的。下面还需要定义一个标签的描述文件,标签的描述文件的后缀“tld”,

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_1.xsd"
    version="2.1">
    <tlib-version>1.0</tlib-version>
    <short-name>firsttag</short-name>
    <tag>
    <name>hello</name>
    <tag-class>org.lxh.tagdemo.HelloTag</tag-class>
    <body-content>empty</body-content>
    </tag>
</taglib>

之后是JSP中的用法:

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ taglib prefix="mytag" uri="mldn_hello"%>
<html>
<head><title>www.baidu.com</title></head>
<body>
    <h1><mytag:hello/></h1>
</body>
</html>

也可以在XML文件中进行设置映射:

        <taglib>
            <taglib-uri>mldn_hello</taglib-uri>
            <taglib-location>/WEB-INF/hellotag.tld</taglib-location>
        </taglib>

在一个JSP文件中,基本功能:判断,输出。所有需要学更多的标签操作。

12.2定义有属性的标签

对于属性:<jsp:forward page=""/>,下载也可以自己定义属性。

下面定义一个可以完成日期格式化显示的操作,希望用户可以输入自己的日期的格式化的模板,根据此模板完成当前日期的显示操作。

标签处理类;

package org.lxh.tagdemo ;
import java.text.* ;
import java.util.* ;
import javax.servlet.jsp.* ;
import javax.servlet.jsp.tagext.* ;
public class DateTag extends TagSupport {
    private String format ;    // 当设置属性的时候可以通过setter完成
    public int doStartTag()
               throws JspException{
        SimpleDateFormat sdf = new SimpleDateFormat(this.format) ;
        // 表示进行格式化的日期显示操作
        try{
            super.pageContext.getOut().write(sdf.format(new Date())) ;
        }catch(Exception e){
            e.printStackTrace() ;    // 异常处理操作
        }
        return TagSupport.SKIP_BODY ;
    }
    public void setFormat(String format){
        this.format = format ;
    }
    public String getFormat(){
        return this.format ;
    }
}

之后编写“tld”文件

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_1.xsd"
    version="2.1">
    <tlib-version>1.0</tlib-version>
    <short-name>datetag</short-name>
    <tag>
    <name>date</name>
    <tag-class>org.lxh.tagdemo.DateTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
        <name>format</name>
        <required>true</required><!--此属性必须设置-->
        <rtexprvalue>true</rtexprvalue><!--支持表达式输出-->
    </attribute>
    </tag>
</taglib>

在xml文件中设置tld文件的路径

    <jsp-config>
        <taglib>
            <taglib-uri>mldn_date</taglib-uri>
            <taglib-location>/WEB-INF/datetag.tld</taglib-location>
        </taglib>
    </jsp-config>

在JSP文件中进行操作:

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ taglib prefix="mytag" uri="mldn_date"%>
<html>
<head><title>www.mldnjava.cn</title></head>
<body>
    <h1><mytag:date format="yyyy-MM-dd HH:mm:ss.SSS"/></h1>
</body>
</html>

此处的format就是标签操作中所需的属性,而此属性操作时,必须有响应的setter()和getter()方法进行接收。

12.3TagSupport类

标签的实现都需要继承TagSupport这个类,所以TagSupport类是整个标签编程的核心类。

首先标签定义完成之后将执行doStartTag()方法,之后判断方法的返回值,如果是返回EVAL_BODY_INCLUDE则表示要执行标签体:(doAfterTag()),如果返回的SKIP_BODY,表示标签准备结束了。

下面为了进一步巩固来定义一个有标签体的标签库。

本程序完成一个判断的操作,判断在某一属性范围内,是否存在指定的属性名称,若存在则输出。

支持标签类:

package org.lxh.tagdemo ;
import java.io.* ;
import javax.servlet.jsp.* ;
import javax.servlet.jsp.tagext.* ;

public class AttributeTag extends TagSupport {
	private String name ;	// 接收属性的名称
	private String scope ;	// 接收属性的范围
	
	public int doStartTag()
               throws JspException{	// 是判断属性是否存在
		Object value = null ;
		if("page".equals(this.scope)){	// 是否是page范围
			value = super.pageContext.getAttribute(this.name,PageContext.PAGE_SCOPE) ;
		}
		if("request".equals(this.scope)){	// 是否是request范围
			value = super.pageContext.getAttribute(this.name,PageContext.REQUEST_SCOPE) ;
		}
		if("session".equals(this.scope)){	// 是否是session范围
			value = super.pageContext.getAttribute(this.name,PageContext.SESSION_SCOPE) ;
		}
		if("application".equals(this.scope)){	// 是否是request范围
			value = super.pageContext.getAttribute(this.name,PageContext.APPLICATION_SCOPE) ;
		}
		if(value == null){	// 表示现在根本就没有此属性
			return TagSupport.SKIP_BODY ;	// 没有属性不执行标签体
		} else {
			return TagSupport.EVAL_BODY_INCLUDE ;	// 执行标签体
		}
	}

	public void setName(String name){
		this.name = name ;
	}
	public void setScope(String scope){
		this.scope = scope ;
	}
	public String getName(){
		return this.name ;
	}
	public String getScope(){
		return this.scope ;
	}
}

需要定义tld文件:

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_1.xsd"
    version="2.1">
    <tlib-version>1.0</tlib-version>
    <short-name>mldntag</short-name>
    <tag>
	<name>present</name>
	<tag-class>org.lxh.tagdemo.AttributeTag</tag-class>
	<body-content>JSP</body-content>
	<attribute>
		<name>name</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
	<attribute>
		<name>scope</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
    </tag>
</taglib>

定义tld路径映射的xml文件:

<web-app 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-app_2_5.xsd"
   version="2.5">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
	<jsp-config>
		<taglib>
			<taglib-uri>mldn_date</taglib-uri>
			<taglib-location>/WEB-INF/datetag.tld</taglib-location>
		</taglib>
		<taglib>
			<taglib-uri>mldn</taglib-uri>
			<taglib-location>/WEB-INF/mldntag.tld</taglib-location>
		</taglib>
	</jsp-config>
	<resource-ref>
		<res-ref-name>jdbc/mldn</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>
</web-app>

完成JSP文件:

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ taglib prefix="mytag" uri="mldn"%>
<html>
<head><title>www.mldnjava.cn,MLDN高端Java培训</title></head>
<body>
	<%
		String scope = "session" ;	// 假设现在判断的是session范围
		session.setAttribute("username","李兴华") ;
	%>
	<mytag:present name="username" scope="<%=scope%>">
		<h2><%=scope%>范围存在属性,内容是:“${sessionScope.username}”</h2>
	</mytag:present>
	<mytag:present name="allusers" scope="request">
		<h2>request范围存在属性,内容是:“${requestScope.allusers}”</h2>
	</mytag:present>
</body>
</html>

关于自定义标签的学习看书实在费劲,而且涉及的类比较多,所以我选择看视频,然后和通过笔记进行学习。我所选择的是李兴华老师的视频讲解,讲得很详细,推荐大家去学习李兴华老师的课程。

                                                                                                                                                             2018 07 17

猜你喜欢

转载自blog.csdn.net/qq_40369435/article/details/81081697