自定标签中获取动态属性:
package com.base;
import java.util.*;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class DynamicAddTag extends SimpleTagSupport implements DynamicAttributes
{
private Map<String, Float> num = new HashMap<String, Float>();
public void doTag() throws JspException, IOException
{
Float sum = 0.0f;
Iterator<Map.Entry<String, Float>> iter = this.num.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry<String, Float> value = iter.next();
sum += value.getValue();
}
super.getJspContext().getOut().write(sum + "");
}
public void setDynamicAttribute(String uri, String localName, Object value) throws JspException
{
// 取出设置的每一个动态属性,都保存在Map集合里
num.put(localName, Float.parseFloat(value.toString()));
}
}
public class Check
{
public static boolean check(String str)
{
if (str.equals("123"))
{
return true;
}
else
{
return false;
}
}
}
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.1</tlib-version>
<short-name>pxl</short-name>
<uri>http://my.tag</uri>
<tag>
<name>add</name>
<tag-class>com.base.DynamicAddTag</tag-class>
<body-content>empty</body-content>
<dynamic-attributes>true</dynamic-attributes>
</tag>
<function>
<name>check</name>
<function-class>com.base.Check</function-class>
<function-signature>boolean check(java.lang.String,)</function-signature>
</function>
</taglib>
页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="pxl" uri="http://my.tag"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>这是测试</title>
</head>
<body>
<c:set var="str" value="23"></c:set>
<c:choose>
<c:when test="${pxl:check(str)}">
<pxl:add num1="32.1" num2="12.4" num3="12.3" />
</c:when>
<c:otherwise>
<c:out value="other"></c:out>
</c:otherwise>
</c:choose>
</body>
</html>