Use and share a class in JSP pages Tag(s): Servlet/JSP


I have a class
public class Hello {
  public String say() {
    return "Hello";
  }
}
and I need to use it in many JSP pages using
<%= say() %>

They are many to achieve that goal :

  • Create a Java class with the method in it, compile it, and deploy the resulting .class file(s) in your webapp's WEB-INF/class directory.
    <%
    Hello h = new Hello();
    out.print(h.say());
    %>
    

  • Create a JAR file containing the .class file(s) and deploy the resulting JAR file via your webapp's WEB-INF/lib directory.
    <%
    Hello h = new Hello();
    out.print(h.say());
    %>
    

  • Create a tag library for it, deploy it via the webapp's WEB-INF/tld directory.

    TAG source code

    TAG source code :
    
    package test;
    
    import java.io.*;
    import javax.servlet.jsp.*;
    import javax.servlet.jsp.tagext.*;
    
    public class HelloTag extends TagSupport  {
      public int doStartTag() throws JspException
      {
        try {
          pageContext.getOut().println("Hello");
        } catch (IOException e) {
        }
        
        return SKIP_BODY;
      }
    }
    the resulting class should go in the WEB-INF/class directory.

    TLD configuration (in the WEB-INF/tlds as hello.tld)

    <taglib>
      <tag>
        <name>hello</name>
        <tagclass>test.HelloTag</tagclass>
      </tag>
    </taglib>
    and to use the tag
    <%@ taglib prefix="ht" uri="WEB-INF/tlds/hello.tld" %>
    ...
    <ht:hello/>
    

  • Create the desired method at the top of the page and copy it from page to page
    <%!
        public static String say() {
          return "Hello";
        }
    %>
    

  • Create an "include file" (say hello.inc), place the method noted above in it, and include it at the top of each JSP page
    <%@ include file="hello.inc" %>
    

    blog comments powered by Disqus