按名称动态调用JSP标记 [英] Call JSP tag dynamically by name

查看:42
本文介绍了按名称动态调用JSP标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以动态使用JSP定制标记? 我有一个代表标签名称的变量,我想调用标签,但要避免使用switch语句.

Is there a way to use JSP custom tags dynamically? I have a variable that represents the name of the tag and I want to call the tag but to avoid switch statements.

示例: 我有标签<my:foo attr="fooAttr" />和标签<my:bar attr="barAttr" />,而不是<c:set var="tagName" value="foo" />.我想以某种方式使用tagName变量来调用标签.

Example: I have tags <my:foo attr="fooAttr" /> and tag <my:bar attr="barAttr" />, than I have <c:set var="tagName" value="foo" />. I want to somehow use the tagName variable to call the tag .

推荐答案

我了解您的担忧...是不是类似<tags:${ tagname }/>的东西?这样的解决方案确实很诱人,但它涉及修改JSP规范以接受不属于XML规范的动态命名标签.

I understand your concern... Something like <tags:${ tagname }/>, isn't it? Such a solution is tempting indeed, but it would involve modifying the JSP specification to accept dynamically named tags that aren't part of the XML specification.

一种半动态"但简单的解决方案可以包括创建一个封装开关逻辑的标签.它可能看起来像:

A "semidynamic" but simple solution could consist in creating a tag that encapsulates the switching logic. It could look like:

<%@ tag body-content="empty" %>
<%@ attribute name="tagname" required="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="tags" %>

<c:choose>
  <c:when test="${ tagname == 'tag1'}">
    <tags:tag1/>
  </c:when>
  <c:when test="${ tagname == 'tag2'}">
    <tags:tag2/>
  </c:when>
</c:choose>

然后,您可以在任何需要的地方使用(和重复使用)以下内容:

Then you could use (and reuse) it wherever you like using something like the following:

<tags:my-switch tagname="${ tagname }"/>

当然,您可以添加可能需要的任何其他属性,并且标记的主体不需要为空.实际上,如果需要处理某些标记主体,请修改上面的body-content属性,然后使用<jsp:doBody/>标准标记来处理主体.

Of course, you can add any other attribute you might need, and the body of the tag doesn't need to be empty. In fact, if you need to process some tag body, modify the body-content attribute above and process the body using the <jsp:doBody/> standard tag.

希望这可以满足您的需求...

Hope this will fulfil your needs...

杰夫

这篇关于按名称动态调用JSP标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆