jsp中自定义标签的学习

xiaoxiao2021-02-28  132

自定义标签概述

在web界面中我们使用了jstl标签 这个jstl标签就是开发javaEE的人员暗转jsp页面上最常用的一些逻辑操作 设计开发的标签,运行时也会翻译成java代码 那么我们也可以自己开发自己需要的页面标签

自定义标签实现

要实现自定义标签,让我们先来了解一下标签的分类,然后再来一一实现自定义标签。 1单标签

<br/>

2有内容的标签

<p></p>

3有参数还有内容的标签

<a href="xxxx">yyyyy</a>

在web工程下web下的WEV-INF文件夹下新建一个后缀为.tld的文件里面内容如下

<?xml version="1.0" encoding="UTF-8"?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee" version="2.1"> <description>myFirstTag</description> <display-name>testTag</display-name> <tlib-version>1.0</tlib-version> <short-name>Tag</short-name> <uri>http://testTag/hello</uri> <tag> <name>hello</name> <tag-class>tag.HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib>

里面就是一些标签描述,我解释下重要的几个。。。

<uri>http://testTag/hello</uri>

注意这个,后面会用到,这里就是相当于一个命名空间的一个什么东西吧,我也不是很明白,希望一起讨论学习。

<body-content>empty</body-content>

这里表示写的是一个单标签,接下来看一下另外一种自定义标签

<tag> <name>bigRed</name> <tag-class>tag.RedTag</tag-class> <body-content>jsp</body-content> </tag>

RedTag是那个类,继续BodyTagSupport 。重写doAfterBody()方法

public class RedTag extends BodyTagSupport { @Override public int doAfterBody() throws JspException { //获得标签中的文本内容 BodyContent bc=this.getBodyContent(); //获得网页中标签的内容 String content=bc.getString(); //获得对象往网页的输出流 JspWriter out=bc.getEnclosingWriter(); try { out.print("<span style='color:red;font-weight:bold'>"+content+"</span>"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.EVAL_PAGE; //return super.doAfterBody(); } }

然后再jsp中这样引用

<tag:bigRed >您的用户名密码错误</tag:bigRed>

ok.success

接下来就是有内容有内容还有参数的标签了

<tag> <name>add</name> <tag-class>tag.AddTag</tag-class> <body-content>empty</body-content> <attribute> <name>num1</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>num2</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>

是否支持el表达式

<rtexprvalue>true</rtexprvalue>

看这个AddTag类,继承TagSupport

public class AddTag extends TagSupport { private int num1; private int num2; public int getNum1() { return num1; } public void setNum1(int num1) { this.num1 = num1; } public int getNum2() { return num2; } public void setNum2(int num2) { this.num2 = num2; } @Override public int doStartTag() throws JspException { // TODO Auto-generated method stub // 获得页面上下文 JspContext jc = this.pageContext; // 获得输出流 JspWriter out = jc.getOut(); try { out.print(num1+num2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return EVAL_PAGE; } }

看到45了吧!

转载请注明原文地址: https://www.6miu.com/read-29495.html

最新回复(0)