标签:
前端需要调用后端的配置,想起velocity-tools。然而jsp的话,目前只能想到tag和EL表达式了。
Tag相当好写,jsp2.0提供了简化写法:
编写一个java类:
public class HelloWorldTag extends SimpleTagSupport { public void doTag() throws JspException, IOException{ JspWriter out = getJspContext().getOut(); out.println("Hello Custom Tag!"); } }
然后编写对应tld:
<?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 [url]http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd[/url]" version="2.0"> <tlib-version>1.0</tlib-version> <short-name>Example TLD</short-name> <tag> <name>hello</name> <tag-class>com.test.demo.HelloWorldTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
然后就可以在页面上使用了:
<%@ taglib prefix="ex" uri="/WEB-INF/hello.tld" %>
<ex:hello/>
上述是没有body的tag,如果想要输出body的内容:
新写一个java类:
public class BodyTag extends SimpleTagSupport { StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException{ getJspBody().invoke(sw); JspWriter out = getJspContext().getOut(); out.println(sw.toString()); } }
在原来tld文件里面追加一个tag:
<tag> <name>body</name> <tag-class>com.test.demo.BodyTag</tag-class> <body-content>scriptless</body-content> </tag>
在页面上:
<ex:body> This is message body. </ex:body>
如果想要在tag上追加参数:
public class StandardTag extends SimpleTagSupport { private String message; public void setMessage(String message) { this.message = message; } StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException{ JspWriter out = getJspContext().getOut(); if (message!=null){ //from filed out.println(message); }else{ //from body getJspBody().invoke(sw); out.println(sw.toString()); } } }
在tld中添加一个新tag:
<tag> <name>msg</name> <tag-class>com.test.demo.StandardTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>message</name> <required>false</required> <type>java.lang.String</type> </attribute> </tag>
在页面上使用:
<ex:msg message="show message from para"> </ex:msg> --------------- <ex:msg> if message==null , then show body. </ex:msg>
如果想要使用传参,使用EL表达:
在java类中添加一个static方法:
public static String hello(String name){ return "Welcome: " + name; }
然后在tld中添加:
<function> <name>welcome</name> <function-class>com.test.demo.StandardTag</function-class> <function-signature>java.lang.String hello(java.lang.String)</function-signature> <example>${ex:welcome(‘Ryan‘)}</example> </function>
然后页面上调用:
${ex:welcome(‘Leslie‘)}
reference:
http://www.runoob.com/jsp/jsp-custom-tags.html
https://www.ibm.com/developerworks/cn/java/j-lo-jsp2tag/
标签:
原文地址:http://www.cnblogs.com/woshimrf/p/5779918.html