jsp 自定义标签【继承TagSupport类】【在 tld描述 中声明 代码段变量】 简单例子四

就是在jsp页面中调用变量如<%=a%>

1。标签程序代码实现部分:

package taglib;

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

import org.apache.log4j.Logger;
/**
 *
 * @author zwc
 *
 */
@SuppressWarnings("serial")
public class RandUtils extends TagSupport {
 private Logger logger = Logger.getLogger(RandUtils.class);
 private int scope;
 
 @Override
 public int doEndTag() throws JspException {
  if(scope == 0){
   scope = 1;
  }
  double d = Math.random() * scope;
  pageContext.setAttribute("randValue", d);

注意:这里的key,就是tld中,声明的变量的名称,tld文档就是通过这个key进行关联的
  logger.info("scope: " + scope + "  rand: " + d);
  return EVAL_PAGE;
 }

 @Override
 public int doStartTag() throws JspException {
  return EVAL_BODY_INCLUDE;
 }
 
 
 
 
 public int getScope() {
  return scope;
 }
 public void setScope(int scope) {
  this.scope = scope;
 }
}

2。tld描述文件

<?xml version="1.0" encoding="UTF-8" ?>
<!--
  Copyright 2004 The Apache Software Foundation
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<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_0.xsd"
  version="2.0">
 
 
  <tlib-version>1.0</tlib-version>
 
  <uri>/test-1.0</uri>
  
  
  <tag>


   <name>getRand</name>
   <tag-class>taglib.RandUtils</tag-class>

注意:这段是前面介绍的,参数值的传入,传入一个计算,范围的变量scope
   <attribute>
    <name>scope</name>
    <required>true</required>
    <type>java.lang.Integer</type>
    <description>return scope double</description>
   </attribute>

 


   注意:这段是声明jsp文件中调用的,变量的名称,与pageContext,进行,关联
   <variable>
    <name-given>randValue</name-given> 注意:必须与pageContext的,key相同
    <variable-class>java.lang.Double</variable-class>
    <scope>AT_END</scope>   范围
    <declare>true</declare>     是否,是已经定义过的,
    <description>var in jsp</description>
   </variable>
  </tag>
 
</taglib>

 

3。页面中调用:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="test" uri="/test-1.0"%>


    TestC:<test:getRand scope="100"></test:getRand>
       <%=randValue %>

4。关于,variable属性,的scope ,和declare的说明

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值