jsp自定义标签库开发

来源:互联网 发布:9 9乘法口诀c语言 编辑:程序博客网 时间:2024/06/07 05:08

    1.实现Tag接口。

//标签实现类

package net;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class HelloTag implements Tag {

 private PageContext pageContext;
 private Tag parent;
 @Override
 public int doEndTag() throws JspException {
  // TODO Auto-generated method stub
  try {
   pageContext.getOut().write("hello,world!!!");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return this.EVAL_PAGE;
 }

 @Override
 public int doStartTag() throws JspException {
  // TODO Auto-generated method stub
  
  return this.SKIP_BODY;
 }

 @Override
 public Tag getParent() {
  // TODO Auto-generated method stub
  return parent;
 }

 @Override
 public void release() {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void setPageContext(PageContext arg0) {
  // TODO Auto-generated method stub
 this.pageContext=arg0;
 }

 @Override
 public void setParent(Tag arg0) {
  // TODO Auto-generated method stub
  this.parent=arg0;
 }

}

//标签描述.tld

<?xml version="1.0" encoding="gbk" ?>

<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 web-jsptaglibrary_2_0.xsd"
    version="2.0">
    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>

  <short-name>examples</short-name>
  <uri>/demotag</uri>
  <description>
 A simple tab library for the examples
  </description>

 <tag>
 <description>Outputs Hello, World</description>
        <name>hello_int</name>
 <tag-class>net.HelloTag</tag-class>
 <body-content>empty</body-content>
    </tag>

</taglib>

//在web.xml中指定标签的引用

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 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-app_2_4.xsd">
 <display-name>
 tag</display-name>
 <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
 <taglib>
       <taglib-uri>/demotag</taglib-uri>
      <taglib-location></taglib-location><!-- 没有给定就是在当前目录下-->
 </taglib>
 
</web-app>

//在jsp中使用标签

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/demotag" prefix="d" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<d:hello_int/><!-- 使用标签 ,d是前缀,随意字符,最好有意思-->


</body>
</html>

 


 

原创粉丝点击