JSP Tag Files in subdirectories, using a single taglib prefix. Is that possible?

泪湿孤枕 提交于 2019-12-04 02:34:15

Define them as <tag-file> in a single .tld file which you put in /WEB-INF folder.

E.g. /WEB-INF/my-tags.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"
>    
    <display-name>My custom tags</display-name>    
    <tlib-version>1.0</tlib-version>
    <short-name>my</short-name>
    <uri>http://example.com/tags</uri>

    <tag-file>
        <name>foo</name>
        <path>/WEB-INF/tags/users/foo.tag</path>
    </tag-file>

    <tag-file>
        <name>bar</name>
        <path>/WEB-INF/tags/widgetsA/bar.tag</path>
    </tag-file>

    <tag-file>
        <name>baz</name>
        <path>/WEB-INF/tags/widgetsB/baz.tag</path>
    </tag-file>
</taglib>

Use it in your JSPs as follows

<%@taglib prefix="my" uri="http://example.com/tags" %>
...
<my:foo />
<my:bar />
<my:baz />

A pattern that I follow, even though doesn't address the OP's problem directly, I find it makes the whole situation a lot less painful, which is creating a JSP Fragment where I define all taglibs:

/WEB-INF/views/taglibs.jspf

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ taglib prefix="layout" tagdir="/WEB-INF/tags/layout" %>
<%@ taglib prefix="t_users" tagdir="/WEB-INF/tags/users" %>
<%@ taglib prefix="t_widgetsA" tagdir="/WEB-INF/tags/widgetsA" %>
<%@ taglib prefix="t_widgetsB" tagdir="/WEB-INF/tags/widgetsB" %>

And then include this JSP Fragment at the top of every JSP file:

/WEB-INF/views/users/employeeProfile.jsp

<%@ include file="/WEB-INF/views/taglibs.jspf" %>

<layout:main>
    <h1>Employee Profile</h1>
    ...
</layout:main>

Should work. Folder names under the specified tag-dir value become hyphen-separated parts of the tag names you would use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!