最近学习java设计模式,在IBM中国网站上学习了repeated menu模式的规则,如果页面内容不得不
超出一屏,菜单将在 Web 页面上重复显示。其顺便提到了自定义标签库,那我也顺便做一下笔记。
呵呵。。。
第一步:需要自定义一个tld文件,如menutaglib.tld。其内容布局如下:
<!DOCTYPE taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlib-version>1.1</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>menu</short-name>
<uri></uri>
<tag>
<!--tag名称-->
<name>topmenu</name>
<!--该tag的处理类-->
<tag-class>com.stereobeacon.patterns.web.menu.MenuPattern</tag-class>
<body-content>empty</body-content>
</tag>
<tag>
<name>bottommenu</name>
<tag-class>com.stereobeacon.patterns.web.menu.MenuPattern</tag-class>
<body-content>empty</body-content>
</tag>
<tag>
<name>movietopmenu</name>
<tag-class>com.stereobeacon.patterns.web.menu.MovieOrderMenus</tag-class>
<body-content>empty</body-content>
</tag>
<tag>
<name>moviebottommenu</name>
<tag-class>com.stereobeacon.patterns.web.menu.MovieOrderMenus</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
第二步:既然定义了tag处理类,那么我们接下来就要建立tag处理类,这些处理类继承了tagSupport类,
并重写doStartTag方法。具体代码如下所示:
public class MenuPattern extends TagSupport {
private static final String homeLink = "<a href=/"menu.jsp/">Home</a>";
private static final String movieLink = "<a href=/"ordermovieplaceholder.jsp/">Order Movies</a>";
private static final String helpLink = "<a href=/"help.jsp/">Help</a>";
public int doStartTag() throws JspException
{
try {
pageContext.getOut().println("<hr>");
pageContext.getOut().println(homeLink);
pageContext.getOut().println(" | ");
pageContext.getOut().println(movieLink);
pageContext.getOut().println(" | ");
pageContext.getOut().println(helpLink);
pageContext.getOut().println("<hr>");
} catch(IOException ioe) {
throw new JspException(
"Error: IOException while writing to client"
+ ioe.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() throws JspException
{
return EVAL_PAGE;
}
}
第三步:服务器在启动的时候需要将该menutaglib.tld,则可以再web.xml中添加相应的说明,具体如下:
<taglib>
<taglib-uri>menutags</taglib-uri>
<taglib-location>/WEB-INF/jsp/menutaglib.tld</taglib-location>
</taglib>
第四步:这个时候万事俱备,只欠东风了,即如何在jsp页面中运用该标签了。具体如下:
<%@ taglib uri="menutags" prefix="menu" %>
<HTML>
<HEAD>
<TITLE>Menu Example</TITLE>
</HEAD>
<BODY>
<menu:topmenu/>
<menu:bottommenu/>
</BODY>
</HTML>
好了,自定义标签完成了,赶紧启动tomcat来运行,看看其效果。