zoukankan      html  css  js  c++  java
  • 一个简单的jsp自定义标签

    学到了一个简单的jsp自定义标签,后面有更多的例子,会更新出来:

    例子1:

    步骤:
    1.编写标签实现类:
      继承javax.servlet.jsp.tagext.SimpleTagSupport;
      重写doTag,实现在网页上输出;
    2.在web-inf目录或其子目录下,建立helloword.tld文件,即自定义标签的说明文件
      注意:标签处理类必须放在包中,不能是裸体类;不需要修改web.xml;
      //tld: tag lib description 标签库描述
     
    java代码:
    package com.mytag;
    
    import java.io.IOException;
    import javax.servlet.jsp.JspException;
    
    public class HelloTag extends javax.servlet.jsp.tagext.SimpleTagSupport{
    
        @Override
        public void doTag() throws JspException, IOException {
            //拿到当前这个jsp文件的上下文,拿到输出流
            getJspContext().getOut().write("HelloWorld!");
        }
    }

    jsp代码:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib uri="/helloworldtaglib" prefix="mytag"%>
    <!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>测试自定义jsp tag标签</title>
    </head>
    <body>
         <mytag:helloworld/>
    </body>
    </html>

    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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0">
    
      <tlib-version>1.0</tlib-version>
      <short-name>mytag</short-name>
      <uri>/helloworldtaglib</uri>
      <tag>
        <name>helloworld</name>
        <tag-class>com.mytag.HelloTag</tag-class>
        <body-content>empty</body-content>
      </tag>       
    </taglib>
    
    <!-- 解释: -->
    <!-- short-name: 这个标签的前缀名 这里就是<mytag: /> 可以防止和别人定义的标签重名的冲突-->
    <!-- uri: 当前这个tld文件要访问它的时候使用的独一无二的标示符,用来找相应的tld文件 -->
    <!-- body-content: 开始标签和结束标签之间的信息,标签体; 如<img/>标签体就是空的 -->
    <!-- tomcat看到<mytag:helloworld/>的helloworld时候,就在tab下面找name=helloworld对应的class,调用doTag方法 -->

    因为我这里的tld文件是放在/WEB-INF/tags/下面的,要配置web.xml文件:加上配置:

    <jsp-config>
            <taglib>
                <!--标签库的uri路径即jsp头文件中声明<%@ taglib uri="/helloworldtaglib" prefix="mytag"%>的uri-->
                <taglib-uri>/helloworldtaglib</taglib-uri>
                <taglib-location>/WEB-INF/tags/helloworld.tld</taglib-location>
            </taglib>
      </jsp-config>

    输出结果:

    后面有其他的用到的,继续更新》。。。。。

  • 相关阅读:
    重打技术征集系统第七稿开发第1、2天
    关于centos7右上角网络图标消失的解决办法
    记录一下hbase踩的坑
    在jsp中,单选按钮的点击事件(点击隐藏或显示输入框)
    input中禁止输入特殊字符
    《软件方法》阅读笔记——1
    随手快递app开发第十七天
    Codeforces Round #284 (Div. 1) B. Name That Tune(最大流)
    hihocoder 1310岛屿(dfs,一个搜索技巧)
    Codeforces Round #294 (Div. 2) E. A and B and Lecture Rooms(lca+思维,树上寻找与给定两个点距离相等的点的个数)
  • 原文地址:https://www.cnblogs.com/tenWood/p/6260825.html
Copyright © 2011-2022 走看看