自定义标签的初步入门

来源:互联网 发布:知乎北京五中大厂分校 编辑:程序博客网 时间:2024/06/03 17:58

在web工程中,经常会用到自定义标签,为此本文编制一个比较两个数据大小并返回最大值的自定义标签,通过此简单标签的编制流程来理解自定义标签的内涵,初步了解自定义标签:
第一步创建一个标签处理器类:实现SimpleTagSupport类

import javax.servlet.jsp.tagext.SimpleTagSupport;public class MaxTag extends SimpleTagSupport{    //获取标签中的属性值    private String num1;    private String num2;    public void setNum1(String num1) {        this.num1 = num1;    }    public void setNum2(String num2) {        this.num2 = num2;    }    @Override    public void doTag() throws JspException, IOException {         int a=0;         int b=0;         JspWriter out=pageContext.getOut();         try {             a=Integer.parseInt(num1);             b=Integer.parseInt(num2);             out.print(a>b?a:b);            } catch (Exception e) {             out.print("输入的属性的格式不正确");        }    }    //获取pageContext对象    private PageContext pageContext;    @Override    public void setJspContext(JspContext arg0) {        this.pageContext=(PageContext) arg0;    }}

第二部:在WEB-INF文件夹下新建一个.tld(标签库描述文件)为扩展名的xml文件

<?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">    <!-- 描述TLD文件 -->  <description>MyTag 1.0 core library</description>  <display-name>MyTag core</display-name>  <tlib-version>1.0</tlib-version>  <!--建议在JSP页面上使用的标签的前缀-->  <short-name>atguigu</short-name>  <!--     作为tld文件的id,用来唯一标示当前的TLD文件,多个TLD文件的URI不能重复    通过JSP页面的taglib标签uri属性来引用  -->  <uri>http://www.atguigu.com/mytag/core</uri>      <tag>        <name>max</name>        <tag-class> com.atguigu.javaweb.tag.MaxTag</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>  </taglib>

第三步:在jsp页面上使用自定义标签

<%@ page language="java" contentType="text/html; charset=gbk"    pageEncoding="UTF-8"%><!--导入标签库(描述文件)  --><%@taglib uri="http://www.atguigu.com/mytag/core" prefix="atguigu"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>     <!--              atguigu:标签前缀        max:标签名        num1、num2属性名      -->     <atguigu:max num1="${param.a}" num2="${param.b}"/></body></html>

第四步运行jsp页面
采用get请求方式,访问地址后面请求参数a=10和b=20;最终页面显示的结果为20;

这里写图片描述

页面返回的结果为最大值20

0 0
原创粉丝点击