JSP:自定义标签的应用

建立自定义标签需要4步(这里以大写标签为例)

1,建立功能实现类-TagBody类

package Test;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class TagBody extends BodyTagSupport {

	public int doEndTag() throws JspException {

		String ct = this.getBodyContent().getString();
		// 获取标签体的代码
		try {
			// 以大写输出
			this.pageContext.getOut().print(ct.toUpperCase());
		} catch (IOException e) {
		}
		return EVAL_PAGE;
	}
}

2,建立标签文件.tld文件

在WEB_INF的目录下

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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">
 <tlib-version>1.0</tlib-version>
 <short-name>toUpperCase</short-name>
 	<tag>
 		<name>toupp</name>
 		<tagclass>Test.TagBody</tagclass>    //标签类的路径
 		<bodycontent>JSP</bodycontent>
 	</tag>
</taglib>

3,配置web.xml文件

在<web-app>和<web-app>直接加入下面代码,切记在<web-app>和<web-app>之间,和其他标签体并行

    <jsp-config>
  	<taglib>
  		<taglib-uri>toUpperCase</taglib-uri>
  		<taglib-location>/WEB-INF/tagbody.tld</taglib-location>
  	</taglib>
  </jsp-config>

4,测试页面

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
    <%@taglib uri="toUpperCase"  prefix="toUpperCase"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="GB18030">
<title>Insert title here</title>
</head>
<body>
	<toUpperCase:toupp>hellow java-web</toUpperCase:toupp>
</body>
</html>

结果

猜你喜欢

转载自blog.csdn.net/qq_42192693/article/details/81837808