declare JSP taglib directives in web.xml

2019-02-06 11:22发布

I seem to remember reading that it's possible to declare taglib directives such as:

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

in web.xml. This eliminates the need to duplicate this directive in every JSP file where the taglib is used. Could someone tell me how these directives can be added to web.xml?

2条回答
狗以群分
2楼-- · 2019-02-06 11:49

The taglib element in web.xml serves a different purpose to the taglib directive which you have above.

As David said, the taglib directive is required on each page.

If you have many pages which use common taglibs, you can shortcut this by putting the taglib directives into an include file, and including this file each page. But no matter how you do it, the taglib directive has to be on the page somehow.

That tag you need to include on each page looks like this:

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

If you have a custom taglib in a custom location, you can also specify a location relative to the webapp root:

 <%@ taglib prefix="ex" uri="/taglib.tld" %>

Further reading on the taglib directive

The taglib directive from web.xml maps tag uris to the physical location of your taglib. It is optional since JSP 2.0, as compliant containers will look in a set of standard locations to try to auto-discover the taglib: /WEB-INF and its subdirectories, /META-INF as well for JAR files.

It looks like this, in web.xml:

<taglib>
  <taglib-uri>
    http://www.example.com/taglib
  </taglib-uri>
  <taglib-location>
    /taglib.tld
  </taglib-location>
</taglib>

And the taglib is referenced in the JSP page like this (the taglib directive on each page is unavoidable!):

<%@ taglib prefix="ex" uri="http://www.example.com/taglib" %>

This is equivalent to the second example I gave for the taglib directive above. The biggest difference is in how you point to the taglib location.

This page contains a bit more information.

查看更多
干净又极端
3楼-- · 2019-02-06 12:03

Sorry, you're slightly mistaken. If a page uses a taglib, you have to have a taglib directive for it on the page. You could place the common taglib directives in an include file that all of your pages include with an include directive, but at compile time the taglib directive has to be there.

I prefer to NOT have the taglib elements in the web.xml, and instead have the taglib directive specify the URI value that is used in the "uri" element in the TLD that is inside the taglib jar file in your WEB-INF/lib.

查看更多
登录 后发表回答