jsp 2.0+中的标签文件以及JSP Fragment技术2014-10-27刚进新公司不久,今天在看到项目中用到了.tag文件。刚开始我还以为这个是第三方类似freemarker的模板技术。问了下项目组的其他人员,原来这是jsp2.0以来就有的JSP Fragment技术。以前做项目的时候从来没有用这样的方式,要公用就用用jsp中的include和jsp:include的方式。其实JSP Fragment也有include的作用,但是它更像第三方sitemesh技术,用于网页布局和修饰,可以将网页的内容和页面的结构分离,从而达到页面结构共享的目的。下面的例子来说明怎么使用jsp fragment。官方E文参考文档http://docs.oracle.com/javaee/5/tutorial/doc/bnama.htmlDEMO1 首先在项目的WEB-INF/tags文件中,新建如下内容的tpl.tag文件
<%@ tag language="java" pageEncoding="UTF-8"%><%@ attribute name="title"%><%@ attribute name="tpl1" fragment="true" required="true"%><%@ attribute name="tpl2" fragment="true" required="true"%><%@ attribute name="tpl3" fragment="true" required="true"%><!DOCTYPE html><html><head><meta charset="utf-8"><title>${title}</title><style type="text/css"> #div1,#div2,#div3{width:90%;margin:10px auto;border:10px solid red; }</style></head><body><h1>jsp2.0标签文件</h1><div id="div1"><jsp:invoke fragment="tpl1" /></div><div id="div2"><jsp:invoke fragment="tpl2" /></div><div id="div3"><jsp:invoke fragment="tpl3" /></div><h2>jsp2.0 fragment技术</h2></body></html>
2 创建index.jsp 文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="xjo" tagdir="/WEB-INF/tags"%><xjo:tpl title="jsp标签文件的使用"><jsp:attribute name="tpl1"><h1>tpl1中的内容</h1></jsp:attribute><jsp:attribute name="tpl2"><h1>tpl2中的内容</h1></jsp:attribute><jsp:attribute name="tpl3"><h1>tpl3中的内容</h1></jsp:attribute></xjo:tpl>
3 访问index.jsp页面,效果如下

本栏目更多精彩内容:http://www.bianceng.cn/webkf/JSP/