JSP自定义tag

前端需要调用后端的配置,想起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')}

在spring mvc 中,有个很好用的tag支持类RequestContextAwareTag,下面做一个简单的使用:

public abstract class BaseTag extends RequestContextAwareTag {
    private static final EPCLogger LOGGER = EPCLogger.getLogger(BaseTag.class);
    private static final long serialVersionUID = -6258930875039222435L;
    private BeanUtils beanUtils = new BeanUtils();
    private HandlebarUtils handlebarUtils = new HandlebarUtils();

    public abstract Object getModel();

    public BaseTag() {
    }

    public void renderHandlebarsView(String templateLocation) {
        try {
            Template e = this.handlebarUtils.compile(templateLocation);
            e.apply(this.getModel(), this.pageContext.getOut());
        } catch (Exception var3) {
            LOGGER.error(UITagsSystemEvent.BASE_TAG_ERROR, "Error occurred while rendering handlebars view.", var3);
        }

    }

    public Object getBean(String beanName) {
        Validate.notNull(beanName);
        return this.beanUtils.getBean(this.getRequestContext(), beanName);
    }
}
public class BeanUtils {
    public BeanUtils() {
    }

    public Object getBean(RequestContext requestContext, String beanName) {
        return requestContext.getWebApplicationContext().getBean(beanName);
    }
}

reference:

http://www.runoob.com/jsp/jsp-custom-tags.html

https://www.ibm.com/developerworks/cn/java/j-lo-jsp2tag/

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏C#

DotNet加密方式解析--非对称加密

    新年新气象,也希望新年可以挣大钱。不管今年年底会不会跟去年一样,满怀抱负却又壮志未酬。(不过没事,我已为各位卜上一卦,卦象显示各位都能挣钱...)...

4838
来自专栏大内老A

The .NET of Tomorrow

Ed Charbeneau(http://developer.telerik.com/featured/the-net-of-tomorrow/) Exciti...

31310
来自专栏魂祭心

原 canvas绘制clock

4054
来自专栏码匠的流水账

聊聊NettyConnector的start及shutdown

reactor-netty-0.7.6.RELEASE-sources.jar!/reactor/ipc/netty/NettyConnector.java

841
来自专栏转载gongluck的CSDN博客

cocos2dx 打灰机

#include "GamePlane.h" #include "PlaneSprite.h" #include "BulletNode.h" #include...

5376
来自专栏张善友的专栏

.NET 4 System.Threading.Barrier 类

在Visual Studio 2010 and .NET Framework 4 Training Kit中有个System.Threading.Barrier...

2039
来自专栏菩提树下的杨过

Flash/Flex学习笔记(23):运动学原理

先写一个公用的小球类Ball: package{ import flash.display.Sprite; //小球 类 public class B...

25210
来自专栏张善友的专栏

Miguel de Icaza 细说 Mix 07大会上的Silverlight和DLR

Mono之父Miguel de Icaza 详细报道微软Mix 07大会上的Silverlight和DLR ,上面还谈到了Mono and Silverligh...

2707
来自专栏陈仁松博客

ASP.NET Core 'Microsoft.Win32.Registry' 错误修复

今天在发布Asp.net Core应用到Azure的时候出现错误InvalidOperationException: Cannot find compilati...

4828
来自专栏跟着阿笨一起玩NET

c#实现打印功能

2692

扫码关注云+社区