建立web项目
一、.java
package com.li.tag;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class TagAttribute extends SimpleTagSupport {
// 自定义标签属性
private String message;
// GET & SET
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
StringWriter sw = new StringWriter();
@Override
public void doTag() throws JspException, IOException {
if (message != null && message != "") {
// 从属性中获取使用消息
JspWriter out = getJspContext().getOut();
out.println(message);
} else {
// 从内容体中获取使用消息
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
}
二、.tld (attribute:rtexprvalue的全称是 Run-time Expression Value, 它用于表示是否能够利用JSP表白式)
<?xml version="1.0" encoding="UTF-8"?>
<j2ee:taglib version="2.0" xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://xmlns.jcp.org/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">
<j2ee:tlib-version>0.0</j2ee:tlib-version>
<j2ee:short-name>NMTOKEN</j2ee:short-name>
<!-- tagAttribute.tld -->
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>
<tag>
<name>att</name>
<tag-class>com.li.tag.TagAttribute</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
<required>false</required>
<type>java.lang.String</type>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</j2ee:taglib>
三、.jsp
<%@ page language="java" isELIgnored="false" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="ey" uri="WEB-INF/tagAttribute.tld"%>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.aaaa{width:200px; height: 100px}
</style>
</head>
<body>
<!--3.自定义标签属(1) -->
<ey:att message="myTagAttribute" />
<!--3.自定义标签属性(2) 注意:isELIgnored -->
<% request.setAttribute("myTagAttribute","你好");%>
<ey:att message="${myTagAttribute}" />
</body>
</html>