JSP EL Functions.

JSP El Function

  • An EL function is mapped to a static method of a Java class.
  • EL function mapping is specified within a tag library descriptor (TLD).
  • EL Function can appear either in template text or in the attributes of a custom tag.
  • An EL function can take any number of parameters, and these are again declared in a deployment descriptor.
    Syntax for an EL function:
    ${namespace_name:function_name("param1","param2"...)}
  • The namespace name is declared by using a taglib directive.
    Example:
    <%@ taglib uri="/WEB-IF/taglib.tld" prefix="taglib" %>
    
  • In the taglib file (here taglib.tld) we must specify the function with a function tag.
    Example of the function tag:
    <?xml version="1.0" encoding="UTF-8"?>
    <taglib version="2.1" 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">
      <tlib-version>1.0</tlib-version>
      <short-name>taglib</short-name>
      <uri>/jspfunc</uri>  
      <function>
        <name>function_name</name>
        <function-class>
          package_spec.ClassName
        </function-class>
        <function-signature>
          java.lang.String function_name_Class(java.lang.String, ...)
        </function-signature>
      </function> 
    </taglib>
  • The uri in this file must be specified in the web.xml deployment descriptor.
    Example of this in web.xml:
      <jsp-config> 
        <taglib>
          <taglib-uri>/jspfunc</taglib-uri>
          <taglib-location>
            /WEB-INF/tlds/taglib.tld
          </taglib-location>
        </taglib>
      </jsp-config>

Example of JSP EL Function.

In the example we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is EL_Function).

In this example, we will add two files, header.jsp and footer.jsp.

  • It is customary to place all include files, which are used several times in the WEB-INF folder. Some would also like the include files should have the extension .jspf, but this is not a requirement.
    Here is the file we want to include at the top of all pages:
    <h2 class="siteblue">JSP EL Function</h2>
    <hr>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Header.jsp and folder should be WEB-INF).

    Here is the file we want to include at the bottom of all pages:
    <hr >
    <jsp:useBean id="today" class="java.util.Date" scope="page" />
    <span class="siteblue">Listing date ${today}</span>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Footer.jsp and folder should be WEB-INF).

In this example, we will add one java file, JSPFunctions.java.

  • The java class that shall contain our static functions.
    Here is the JSPFunctions.java:
    package app;
    
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class JSPFunctions {
    
      private static String hostUrl = "";
    
      public static void setHostUrl(String hostUrl) {
        JSPFunctions.hostUrl = hostUrl;
        
      }
    
      public static String drawCircle(int xPos, int yPos, int radius, String color) {
        return readURL("svgCircle.jsp", "xPos=" + String.valueOf(xPos)
                + "&yPos=" + String.valueOf(yPos)
                + "&radius=" + String.valueOf(radius) + "&color=" + color);
      }
    
      private static String readURL(String file, String params) {
        URL url = null;;
        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
          url = new URL(hostUrl + file + "?" + params);
          reader = new BufferedReader(new InputStreamReader(url.openStream()));
          String line = null;
          String ls = System.getProperty("line.separator");
          while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append(ls);
          }
          reader.close();
        } catch (FileNotFoundException ex) {
          Logger.getLogger(JSPFunctions.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
          Logger.getLogger(JSPFunctions.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
          Logger.getLogger(JSPFunctions.class.getName()).log(Level.SEVERE, null, ex);
        } 
        return stringBuilder.toString();
      }
    
    }

    For those who participate in the review: create a java class in Netbeans and replace generated code for the java file with that shown above (the java file name is JSPFunctions and package should be app).

  • The first static function, setHostUrl, sets the host address as we need this in the next static function.
  • The second static function, drawCircle, executes the private function, readURL, that reads and returns contents of a file (svgCircle.jsp).
  • As we read svgCircle.jsp file through a URL, svgCircle.jsp will read parameters provided herein.

Creating the svgCircle.jsp file.

  • Here is our svgCircle.jsp file:
    <svg id="svgCircle" xmlns="http://www.w3.org/2000/svg" 
         width="${param.radius*2+param.xPos}" 
         height="${param.radius*2+param.yPos}"  
         style="position: relative; left: 50px;
         background-color: #ffff00; " >
      <circle cx="${param.xPos}" 
              cy="${param.yPos}" 
              r="${param.radius}" 
              fill="${param.color}"  />
    </svg>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Startup).

  • In this file we read in-given parameters using JSP EL param implicit object.
  • Besides, we use SVG tags to draw graphics.

We must declare all the static functions in a tld file.

  • Here is our taglib.tld file:
    <?xml version="1.0" encoding="UTF-8"?>
    <taglib version="2.1" 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">
      <tlib-version>1.0</tlib-version>
      <short-name>taglib</short-name>
      <uri>/jspfunc</uri>
      <function>
        <name>DrawCircle</name>
        <function-class>app.JSPFunctions</function-class>
        <function-signature>
          java.lang.String drawCircle(int, int, int , java.lang.String )
        </function-signature>
      </function>
      <function>
        <name>SetHostUrl</name>
        <function-class>app.JSPFunctions</function-class>
        <function-signature>
          void setHostUrl(java.lang.String)
        </function-signature>
      </function>  
    </taglib>

    For those who participate in the review: create a tld file in Netbeans and replace generated code for the tld file with that shown above.

  • For each function, we must specify a name EL can use. Furthermore, we must specify the class that contains the function and finally the signature the function has.
  • The function signature must specify the return type, name of the function in the class and all parameter types.
  • Remember to include package specification for all the java class types.

We need a JSP file to demonstrate use of JSP EL Function.

  • <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="taglib" uri="/jspfunc"%>
    <!DOCTYPE html> 
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP EL Funcion</title>
        <style>
          hr { background-color: #3366ff; height: 4px; border: 0; }
        </style>    
      </head>
      <body>
        ${taglib:SetHostUrl(pageContext.request.getRequestURL())}
        <div style="max-width:310px; position:  relative; ">
          <%@ include file="/WEB-INF/header.jsp" %>
          ${taglib:DrawCircle(100, 100, 50, "blue")}
          <%@ include file="/WEB-INF/footer.jsp" %>      
        </div>
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is index).

  • The namespace name, taglib, is declared by using a taglib directive.
  • It is important first to set up url so the function SetHostUrl is executed first.
  • We execute the second function, Draw Circle, after the header.

Creating Deployment descriptor.

  • To run this JSP you have to deploy it to a web-server or a Application server. To deploy means to install the JSP with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
      <servlet>
        <servlet-name>functionApp</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
      </servlet>
      <servlet-mapping>
        <servlet-name>functionApp</servlet-name>
        <url-pattern>/functionApp</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>functionApp</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a JSP file.
  • With a servlet tag we give the JSP file a servlet name, which is used in the servlet-mapping tag to specify a url for the JSP file.
  • In this way we can have many urls for the same JSP file.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file with url functionApp. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /EL_Function) for the application will in most cases be specified by a server vendor deployment descriptor.
    The browser will display:
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.