自定义JSTL标签


有时候会遇到需要在JSP中调用Java方法的情况,这个问题可以通过自定义JSTl标签的方法解决。

步骤:

  1,准备好Java方法,这里需要注意的是,这个方法必须要是静态static修饰的

  2,创建一个tld文件,将准备的方法添加到tld文件中,然后将tld映射添加到web.xml文件中

  3,然后就可以在jsp中调用了

 

下面是我的示例:

  1,java类

public class DataDictionaryUtil {

    public static String getMean(String type,String num){
        
        if ("bussinessType".equals(type)) {
            //业务种类
            if ("1".equals(type)) {
                return "贷款";
            }else if("2".equals(type)){
                return "信用卡";
            }else{
                return null;
            }
        }
    return null;
    }

}

 

  2,tld文件(一般都放在WEB-INF目录下)

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
    
  <description>JSTL 1.1 functions library</description>
  <display-name>JSTL functions</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>fn</short-name>
  <uri>http://java.sun.com/jsp/jstl/functions</uri>

<!-- 添加自定义方法 -->
  <function>
      <name>getMean</name>
      <function-class>com.wangyin.credit.report.util.DataDictionaryUtil</function-class>
      <function-signature>java.lang.String getMean(java.lang.String,java.lang.String)</function-signature>
      <example>${fn.getMean(type,code)}</example>
  </function>

</taglib>

  

  web.xml文件映射配置(配置在根标签下)

<jsp-config>
    <taglib>
        <taglib-uri>/credit</taglib-uri>
        <taglib-location>/WEB-INF/dtl/credit.tld</taglib-location>
    </taglib>
</jsp-config>

 

  3,在jsp中调用自定义标签

  •  先将自定义标签进行引入
<%@ taglib prefix="credit" uri="/credit" %> 
  • 然后在页面中进行调用
业务种类信息:${credit:getMean('bussinessType','1')}

(备注:这里传递参数的时候,单引号,双引号都可以,1也可以不加引号)

  4,然后,如果没有意外的话,你想要的结果就出现了!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM