jsp自定义标签自学笔记(二)

上一回学习了自定义标签库的写法。但是“hello world”级别的标签是远远不能满足我们如狼似虎的求知欲的。这回写个带名字的输入框。(知识就像美女,勇敢的扑过去吧!)

1、InputTag.java
package fox.tags.hello;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class InputTag extends TagSupport{
	
	private String name="";

	public void setName(String name) {
		//set方法必须有
		this.name = name;
	}

	@Override
	public int doStartTag() throws JspException {
		return normalInput();
	}
	
	private int normalInput(){
		JspWriter out=this.pageContext.getOut();
		StringBuffer sb=new StringBuffer("");
		sb.append("<input type=\"text\" name=\"");
		sb.append(name);
		sb.append("\"/>");
		try {
			out.write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return this.SKIP_BODY;
	}
	
}


2、hello.tld
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
                        "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
 <tlib-version>1.0</tlib-version>
 <jsp-version>1.2</jsp-version>
 <short-name>shortname</short-name>
 <tag>
  <name>hello</name>
  <tag-class>fox.tags.hello.HelloTag</tag-class>
 </tag>
 <tag>
 	<name>einput</name>
 	<tag-class>fox.tags.hello.InputTag</tag-class>
 	<attribute>
 		<name>name</name>
 		<required>false</required>
 		<!-- rtexprvalue的全称是 Run-time Expression Value, 它用于表示是否可以使用JSP表达式. -->
 		<rtexprvalue>true</rtexprvalue>
 	</attribute>
 </tag>
</taglib>


3、web.xml的配置和(一)是相同的
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <jsp-config>
  	<taglib>
  		<taglib-uri>/hello-tags</taglib-uri>
  		<taglib-location>/WEB-INF/tld/hello.tld</taglib-location>
  	</taglib>
  </jsp-config>
</web-app>


4、引用自定义的标签
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="/hello-tags"  %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <f:hello></f:hello><br/>
    <f:einput name="myname"></f:einput>
  </body>
</html>

你可能感兴趣的:(java,Web,jsp,xml,servlet)