Posts Tagged ‘taglib’
  • Do not use taglibs, use tagfiles!

    Taglibs are wonderful components available since J2EE 1.3. They enable you, as developer:

    • to refrain from using too much scriptlets (free-form Java code) in your Java Server Pages,
    • to have a library of reusable components that can be distributed to all your projects.

    Both are very important in the enterprise as of now. For example, as an architect, you can disallow the use of scriptlets altogether and then provide taglibs to restrain what can be done on the page. Such policies are not uncommon and can be enforced by quality code checkers. It prevents fresh-out-of-school developers to call JDBC code in the JSP, thus destroying your precicous Model View Controller model.

    Taglibs have a big drawback, though: they are standard Java classes that inherit the right class (javax.servlet.jsp.tagext.Tag or javax.servlet.jsp.tagext.SimpleTag). Thus, their content must be written to the JspWriter. In that, they are very similar to Servlets: they cannot be designed by a graphist and you must provide an servlet engine to see their output. Servlet have JSP to serve as view, taglibs have tagfiles!

    What is a tagfile, anyway? Just put a file with a *.tag extension in your /WEB-INF/tags directory, and bingo, you have a tagfile. In order to test the creation of tagfiles, create a hello.tag with the following content: “Hello world”. Then create a JSP and paste the following snippet:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    <%@ taglib prefix="tag" tagdir="/WEB-INF/tags"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Tag files example</title>
    <tag:hello />

    You can already guess the output. The little magic comes in referencing the tagfile. We do not use the uri attribute of the taglib directive but the tagdir attribute that tells the application server where we stored our tagfiles. To call the tagfile, use the prefix as usual and then the name of the file. No need to use a TLD. Easy, isn’t it?

    To easy… In fact, this use of tagfiles does not enable reuse. It is done in the context of a single web application and has not many advantages over use of JSP includes. To package tagfiles for reuse, you’ll have to move the files from /WEB-INF/tags to /META-INF/tags and create a full fledged TLD under /META-INF:

    <?xml version="1.0" encoding="UTF-8"?>
    <taglib version="2.0" xmlns=""
        xmlns:xml="" xmlns:xsi=""
        xsi:schemaLocation=" ">
        <!-- don't use tagclass -->

    Now use the taglib in a JSP (don’t forget to use the uri attribute now). The result should be the same, but now you have a reusable component per-se. Of course, writing a string in the output is not very useful. Like taglibs, tagfiles can accept variables. It is very easy to do this, because many attributes which are found under the TLD with taglibs are found in the tagfile itself. Let’s write a tagfile that write today’s date with the format given by the developer:

    <%@ tag body-content="empty" %>
    <%@ attribute name="format" required="true" %>
    <%@ taglib prefix="fmt" uri="" %>
    <jsp:useBean id="date" class="java.util.Date" />
    <fmt:formatDate value="${date}" pattern="${format}" />

    Notice the attribute syntax.

    Eclipse project for these examples can be found here.

    To go further:

    Categories: JavaEE Tags: tag filetag libtagfiletaglib
  • Decrease your pages load time

    1. Generalities

    Web applications have several advantages over traditional client server applications: since business code comes from a unique server (forget clustering here), they are always up-to-date. Moreover, deployment of a new version is only a matter of minutes.

    They have one big drawback, though. Since HTML code is sent through the network, responsiveness is generally much less than that of traditional applications.

    The responsiveness of an interactive system describes how quickly it responds to user input (i.e. the rate of communication with the system).
    -- From Wikipedia

    Ajax overcomes some of this in proposing to load the entire page at start and the modifiying pertinent chuncks of it. Yet, it is only part of the solution, since initial loading of the page will be the hardest on the user. Users don’t like waiting for a page to load. As a user, you don’t like waiting. As a good rule of thumb, you must make every effort to achieve a initial page load time of less than 1 second (you can find additional informations on load time steps in this very interesting article). This load time doesn’t cover the time for the entire page and style sheets and scripts to finish downloading, but only the time for the user to have pertinent informations displayed and to begin interacting with the screen. This is of cours very context dependent but conclusion is: the less time your page takes to display, the better it is.

    2. Decreasing load time

    Yahoo provides 34 best practices to speed up your site. If you use Mozilla Firefox, and you already use the fantastic FireBug plug-in, you should add the YSlow plugin to it (if not, download FireBug beforehand). YSlow checks the web page you’re browsing with Firefox for 13 of these rules. The important rules for the matter at hand are:

    1. Make JS and CSS external,
    2. Make fewer HTTP requests,
    3. Minify JS (and CSS).

    First point is pretty self-explanatory. Instead of putting JS code and CSS information in your HTML, you put both in external files and reference these from your page: no big deal, everybody does it nowadays. The second point is contrary to the first: for each file you have, you must make a separate HTTP request. So, the best solution is your main HTML plus a single JavaScript file and a single CSS file. The 3rd point is to minify those files, that is to remove comments, extra spaces and linebreaks, so as to make those files lighter. Options also include renaming the variables to make their names shorter (which can obsfuscate, deliberately or not).

    3. Minification at build time

    Among all the tools avalaible, a good one for minifying JS and CSS (starting from v2.0) is Yahoo UI Library Compressor. It is developed in Java and can be runned from the command line. Such command can take place during the build process. The following Ant task executes the minifying process on simple.js :

    <!-- Executes YUI compressor on simple JS file -->
    <target name="simplest">
      <java jar="tools/yuicompressor-2.4.2.jar" fork="true">
        <arg value="-v" />
        <arg value="web/script/simple.js" /&>

    The main drawback of this solution is that you lose your original script in favor of the minified one. YUI compressor enables to output the minified script in a new script, hence the following Ant target :

    <!-- Executes YUI compressor on simple JS file -->
    <target name="simple">
      <java jar="tools/yuicompressor-2.4.2.jar" fork="true">
        <arg value="-v" />
        <arg value="web/script/simple.js" />
        <arg value="-o" />
        <arg value="${build.dir}/web/script/simple.js" />

    This makes the process slightly better. Yet, I cannot test the minified script under my favourite IDE because the script is only correct in the WAR creation scope, not in the deploy-in-IDE scope.

    4. Minification at runtime

    In order to prevent this drawback, we could make the minifying a runtime process. In order to do this, we create a filter that is associated with .js extensions :

    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
     * Filter that minifies JavaScript files. Can be used with CSS files with less configuration.
     * @author Nicolas Fränkel
     * @since 17 mars 2009
    public class YuiCompressorFilter implements Filter {
        /** Configuration object. */
        private FilterConfig config;
        /** Number of kept linebreaks. */
        private int linebreak;
        /** Munge. */
        private boolean munge;
        /** Verbose. */
        private boolean verbose;
        /** Should all semicolons be kept. */
        private boolean preserveAllSemiColons;
        /** Should optimization be disabled. */
        private boolean disableOptimizations;
         * This implementation does nothing.
         * @see javax.servlet.Filter#destroy()
        public void destroy() {}
         * Compress JS and CSS output.
         * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
         *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
          throws IOException, ServletException {
    	StringWriter stringWriter = new StringWriter();
    	final PrintWriter printWriter = new PrintWriter(stringWriter);
    	HttpServletRequest httpRequest = (HttpServletRequest) request;
    	String path = httpRequest.getServletPath();
    	InputStream stream = config.getServletContext().getResourceAsStream(path);
    	Reader source = new InputStreamReader(stream);
    	JavaScriptCompressor compressor = new JavaScriptCompressor(source, new BasicErrorReporter());
    	compressor.compress(printWriter, linebreak, munge, verbose, preserveAllSemiColons, disableOptimizations);
         * Reads filter parameters.
         * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
        public void init(FilterConfig config) throws ServletException {
            this.config = config;
            String linebreakString = config.getInitParameter("linebreak");
            String mungeString = config.getInitParameter("munge");
            String verboseString = config.getInitParameter("verbose");
            String preserveAllSemiColonsString = config.getInitParameter("preserveAllSemiColons");
            String disableOptimizationsString = config.getInitParameter("disableOptimizations");
            munge = Boolean.parseBoolean(mungeString);
            verbose = Boolean.parseBoolean(verboseString);
            preserveAllSemiColons = Boolean.parseBoolean(preserveAllSemiColonsString);
            disableOptimizations = Boolean.parseBoolean(disableOptimizationsString);
            try {
                if (linebreakString != null) {
                linebreak = Integer.parseInt(linebreakString);
            } catch (NumberFormatException e) {
                throw new ServletException(e);

    Now our compressor works both in and out of our favorite IDE. But the drawback is the performance lost in applying the filter each time the resource is needed. In order to lessen this cost, we could:

    • implement a cache that maps paths to minified scripts (as strings) in memory,</li>
    • rely on the browser cache by using HTTP headers related to expiration values.</li>

    Still, I find this not very satisfying… First of all, YUI compressor was not supposed to be used in this fashion. This shows because you find no documentation, JavaDoc or else, regarding individual use of the methods. Then, the less I code, the better I feel. In this case, I had to code a whole filter, complete with initialization parameter. Last but not least, do you remember the 3 rules, at the top of the article? We adressed only the 3rd point, minifying the script, but in no way did we make fewer HTTP request by using YUI compressor. If we had 15 different source scripts, we would still have 15 minified scripts at the end and thus need 15 HTTP requests to get them all.

    5. Jawr

    Jawr is the solution to our problem: it enables to have different scripts during development (third-party scripts, enterprise framework scripts, applications scripts, etc.) and bundles them at application startup in one big script file. The process is completely transparent to the developer and is lightweight because all work is done at application startup.

    Additional features include:

    • Bundling of any JavaScript or CSS file whatever the chosen directory structure,
    • Modifying those files dynamically, e.g. with ResourceBundle messages,
    • JavaScript and CSS minification (oh, what a surprise!) that can be done with either YUI Compressor or JSMin,
    • Caching enforcement through is a modification of sent HTTP headers,
    • GZip support for compatible browsers.

    In order to do so, Jawr uses 3 kind of components:

    • a servlet to serve JavaScript and CSS content,
    • jawr taglibs that references JS and CSS,
    • a configuration file in Java properties format.

    The configuration of the web deployment descriptor will look something like this:


    An example properties file will look like this

    #Turning on compression when possible
    #Using YUI compressor
    #Bundling into all.js
    #Bundled scripts
    jawr.js.bundle.all.mappings=/script/simple.js, /script/sub/b.js, /script/sub/subsub/a.js

    Then, you will use it like this in your page:

    <%@ taglib prefix="jawr" uri=""%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <titlegt;Jawr test welcome page</title>
        <body onload="a();b()" />
    <jawr:script src="/script/all.js" />

    You will find there a Jawr example project made with Eclipse along with the previous YUI Compressor example. This example shows you the main uses of Jawr, mainly:

    • bundling JavaScript files,
    • minifying them,
    • compressing the bundled file (if you browser supports it).

    As an example, it will only output two JavaScript alert boxes, but it will you the framework to build upon if you need to go further.

    6. Conclusion

    Minifying external files is not the only think of in order to decrease your web pages load time. You should also decrease to the maximum the number of these files. Jawr is an OpenSource component used to do both elegantly: I hope this article convinced you that Jawr is the right tool for this usage.

    Categories: JavaEE Tags: jawrjsptaglibwebyslow
  • VIT: Very Important Taglib

    Display taglib

    Every application needs to display tabulated data. Well, web applications are no different. So, as an architect, your job is to provide a mechanism to handle these tables gracefully and equally in your whole application.

    First thing that comes to mind is the reuse of an existing mechanism to do so. Well, you’re lucky. If you don’t happen to have to use JSF, there’s a neat tag library that handles the job like a pro. For those that don’t remember what a taglib is, please feel free to take a look there, I’m waiting for you so take your time. If you don’t have time to read the tutorial, just know that taglibs are jars, and as such, can be dropped into webapps and used as such.

    The Display tag library provides the followings options out-of-the-box:

    • paging: the ability to display only a subset of a list and to navigate from subset to subset in a ordered way,
    • sorting: the capacity to order a subset of a list, either from the subset or from the entire list,
    • grouping: the aptitude to display an information but only if it is new,
    • export: Excel, CSV, XML are provided but a framework mechanism enables you to write more,
    • formatting: dates come to mind but what about currency, numbers, ...,
    • alternating color lines: a classic one,
    • hyperlinks,
    • internationalization.

    With these few lines of code:

    <display:table name="test" export="true" sort="list" pagesize="8">
              <display:column property="city" title="CITY" group="1" sortable="true" headerClass="sortable" /> 
              <display:column property="project" title="PROJECT" group="2" sortable="true" headerClass="sortable" /> 
              <display:column property="amount" title="HOURS" /> 
              <display:column property="task" title="TASK" /> 

    you get this :

    Display tag example

    Not bad, eh ? Well, this treasure is currently available in version 1.1.1.

    Those of you that have a little experience in the use of external libraries are well aware that, under normal circumstances, this would hint that it won’t fit your every needs and it will be a nightmare to integrate. In this case, it is not the case (really !). The taglib is highly configurable thanks to

    • property files for labels,
    • css for presentation.

    Plus, if this doesn’t cover all your needs (aren’t you the demanding type ?), the API is clear and concise enough to let you develop your own classes. For example, if you have an higly personal class to present in your table, the API lets you do it the precise way you want with the help of the API and the Decorator pattern.

    Icing on the cake: It is brought to you with the open source artistic license. From now on, you have no reason to ignore this little jewel.

    I welcome your comments if you did already used this taglib: was it as nice for you as for me ?

    Categories: JavaEE Tags: displaylibrarytabletabulatedtagtaglib