自定义标签

自定义标签该则么玩呢?有什么用呢?问这些问题证明你的肤浅【/哈哈哈】,其实我也不知道~,不过听人家说可以用来该一个分页标签,听起来不错吧~,后面我们再来试试呢?

废话先不说,上代码:

1.首先我们写一个类,该类用来处理自定义标签的逻辑:

package com.java.tag;

import java.io.IOException;

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

public class HelloWorldTag2 extends TagSupport{

/**
*
*/
private static final long serialVersionUID = 1L;

private String name;//标签的属性

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int doStartTag() throws JspException {//进入页面加载标签的时候就调用该方法
JspWriter out=this.pageContext.getOut();//拿到输出流
try {
out.println(name+"自定义标签!");//向页面输出至
} catch (IOException e) {
e.printStackTrace();
}
return TagSupport.SKIP_BODY; // 直接结束标签
}

}

2.定义好了标签然后呢?然后就没然后了.....

逗你的然后我们就像配置servlet一样需要配置标签,然而并不是在web.xml中配置哈

java.tld配置文件//用来配置自定义标签的

<?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>javaTag</short-name>


<tag>

<!--标签名-->
<name>helloWorld2</name>
<tag-class>
com.java.tag.HelloWorldTag2
</tag-class>
<body-content>empty</body-content>
<attribute>

<!--标签属性--->

<!---是否必须填写-->
<name>name</name>

<!---是否支持el表达式-->
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

3.自定义标签定义完了我们就可以使用咯~

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!---引入我们的标签-->
<%@ taglib prefix="java" uri="/WEB-INF/java.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<java:helloWorld2 name="JspServlet你好"/>
</body>
</html>

posted @ 2017-02-23 07:53  小拽A  阅读(149)  评论(0编辑  收藏  举报