第一步:写标签处理器 public class Mytag extends TagSupport
public class Mytag extends TagSupport {
private UserInfo user;
@Override
public int doStartTag() throws JspException {
try {
JspWriter out = this.pageContext.getOut();
if(user == null) {
out.println("No UserInfo Found...");
return SKIP_BODY;
}
out.println("<table width='500px' border='1' align='center'>");
out.println("<tr>");
out.println("<td width='20%'>Username:</td>");
out.println("<td>" + user.getUserName() + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Age:</td>");
out.println("<td>" + user.getAge() + "</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Email:</td>");
out.println("<td>" + user.getEmail() + "</td>");
out.println("</tr>");
out.println("</table>");
} catch(Exception e) {
throw new JspException(e.getMessage());
}
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
@Override
public void release() {
super.release();
this.user = null;
}
//getter and setters
public UserInfo getUser() {
return user;
}
public void setUser(UserInfo user) {
this.user = user;
}
}
实体类:UserInfo
public class UserInfo {
private String userName;
private int age;
private String email;
第二步:web-Inf下创建myTag.tld文件
<?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>
<jsp-version>2.0</jsp-version>
<short-name>cc</short-name>
<uri>/mytaglib</uri>
<tag>
<name>showUserInfo</name>
<tag-class>myTag.cn.itcast.test.Mytag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>user</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
第三步:显示页面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>自定义标签</title>
</head>
<body>
<!-- 给标签设置user属性绑定要展现的UserInfo对象 -->
<cc:showUserInfo user="${pageScope.userinfo }" />
</body>
</html>
第四步:在显示页面中引入自定义标签,导入初始化实体类信息
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/mytaglib" prefix="cc"%>
<%@ page import="myTag.cn.itcast.test.*"%>
<%
UserInfo user = new UserInfo();
user.setUserName("Xuwei");
user.setAge(33);
user.setEmail("test@test.test");
pageContext.setAttribute("userinfo", user);
%>
第五步:在web.xml下配置自定义标签tld文件
<jsp-config>
<taglib>
<taglib-uri>/mytaglib</taglib-uri>
<taglib-location>/WEB-INF/myTag.tld</taglib-location>
</taglib>
</jsp-config>