在jsp标记文件中的java代码中使用标记属性

时间:2014-11-12 00:06:16

标签: java jsp tomcat tomcat6 jsp-tags

我在<%@attribute name="listname" required="true"%>文件的起始处有一些.tag声明的属性。

我可以使用${listname}打印出来。但是我想在同一页面内的一个java代码中使用这个变量。

类似的东西,

<%
    String listname = ${listname};
    ...Some more code...
%>

我该怎么做。

如果有帮助,我正在使用apache tomcat6。

我是这个环境的新手,甚至是Java。如果我使用了一些错误的术语,请原谅并纠正我。

2 个答案:

答案 0 :(得分:2)

您可以使用jspContext中的属性获取传递给自定义标记的属性: -

<%@ tag description="Category Options" trimDirectiveWhitespaces="true"  pageEncoding="UTF-8" %>
<%@ attribute name="depth" required="false" type="java.lang.Integer" rtexprvalue="true"%>

<%
Integer depth = (Integer)jspContext.getAttribute("depth");
// do stuff with depth
%>

答案 1 :(得分:1)

您是否考虑过在Java类而不是JSP中进行处理?配置与使用.tag文件略有不同:

<强>的web.xml

<jsp-config>
    <taglib>
        <taglib-uri>mytaglib</taglib-uri>
        <taglib-location>/WEB-INF/tags/mytaglib.tld</taglib-location>
    </taglib>
    ...
</jsp-config>

<强> mytaglib.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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 web-jsptaglibrary_2_0.xsd">

    <tlib-version>1.0</tlib-version>
    <short-name>mylib</short-name>
    <uri>/WEB-INF/tags/mytaglib</uri>
    <tag>
        <name>checkbox</name>
        <tag-class>com.myapp.tag.MyTagSupport</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>name</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        ...
    </tag>
    ...
</taglib>

JSP包含

<%@taglib uri="mytaglib" prefix="ml" %>

标记支持类

package com.myapp.tag;

import javax.servlet.jsp.tagext.BodyTagSupport    

public class MyTagSuppoort extends BodyTagSupport {

    private String name = name;

    // Values are autowired by the JSTL API
    public void setName ( String name ) {
        this.name = name;
    }

}

这是如何在标记支持类中实现内容的一个很好的例子:

http://www.tutorialspoint.com/jsp/jsp_custom_tags.htm