自定义JSTL标签

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

自定义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,然后,如果没有意外的话,你想要的结果就出现了!

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航