简体   繁体   中英

JSP - issue with custom Taglib

I just tried to add a custom taglib to my project, such that the testtaglib.tld file contains:

<taglib>
<tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>name</shortname>

    <tag>
        <name>test</name>
        <tagclass>taglib.TestTaglib</tagclass>
        <bodycontent>empty</bodycontent>
        <attribute>
            <name>testCode</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.String</type>
        </attribute>
    </tag>
<taglib>

And then I added taglib class TestTaglib.java

public class TestTaglib extends TagSupport {

    private String  testCode;
    public int doStartTag() throws JspException {
        try {
            JspWriter out = pageContext.getOut();
            //doing some conversion with testCode
            out.print(testCode);
            return EVAL_PAGE;
        } catch(IOException ioe) {
            throw new JspException("Error: " + ioe.getMessage());
        }
    }
}

And then in .jsp file

<name:test testCode="${testCode}"/>

Okay the issue is: TestTaglib.java is recognizing values of testCode as ${testCode} and not the original value. Any suggestion?

Hi all inbuilt tag already handles the expression language. Just change your code as mentioned below and it will work fine.

 public class TestTaglib extends TagSupport {


 private String  testCode;
    public int doStartTag() throws JspException {
        try {
            JspWriter out = pageContext.getOut();
            //doing some conversion with testCode
            String value = (String) ExpressionUtil.evalNotNull("test", "testCode", testCode, String.class, this, pageContext);
            out.print(value);
            return EVAL_PAGE;
        } catch(IOException ioe) {
            throw new JspException("Error: " + ioe.getMessage());
        }
    }
}

ExpressionUtil is class provided under org.apache.taglibs.standard.tag.el.core package.

Here is short desc of evalNotNull method args

your tag name is test 您的标签名称为test
to eval in your case it is testCode 在您的情况下为testCode
which is el expression ${testCode} el表达式$ {testCode}
Class of expression value whether it is Boolean,String or any Object 表达式值的类别,无论是布尔值,字符串还是任何对象
Reference of tag handler class so you can pass this 标记处理程序类的引用,因此您可以传递它
which is coming from TagSupport 来自TagSupport

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM