直接上代码:
public class IncludeTag extends BodyTagSupport {
private static final long serialVersionUID = 3048295381656105593L;
private final String CACHENAME = "TAG_CACHE";
private String content;
@Override
public int doStartTag() throws JspException {
content = (String)CacheHelper.get(CACHENAME);
if(content != null) { //尝试从缓存中读取页面片段
return SKIP_BODY;
}
return super.doStartTag();
}
@Override
public void doInitBody() throws JspException {
//Object obj = CacheHelper.get(...);
//pageContext.getRequest().setAttribute(key, obj);
pageContext.getRequest().setAttribute("key", "value"); //这里可以从缓存中读取相关数据放入request中供页面片段使用
List<String> lst = new ArrayList<String>();
lst.add("item 1");
lst.add("item 2");
pageContext.getRequest().setAttribute("list", lst);
super.doInitBody();
}
@Override
public int doAfterBody() throws JspException {
return super.doAfterBody();
}
@Override
public int doEndTag() throws JspException {
if(content == null){
content = bodyContent.getString().trim();
if(content.length() != 0 || !content.equalsIgnoreCase("null")) {
CacheHelper.set(CACHENAME, content); //设置页面片段到缓存中
}
}
try {
pageContext.getResponse().getWriter().print(content); //输出页面片段内容到页面上
} catch (IOException e) {
e.printStackTrace();
}
return super.doEndTag();
}
}
调用自定义标签的页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="my" uri="/WEB-INF/my.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test</title>
</head>
<body> <my:include> <%@ include file="include.jsp" %> </my:include> </body>
</html>
module.jsp页面的内容:
<%@ page import="java.util.*" %>
<%=request.getAttribute("key") %>
<div>
<ul>
<%
List lst = (List)request.getAttribute("list");
for(int i=0; i<lst.size(); i++) {
%>
<li><%=lst.get(i) %></li>
<%
}
%>
</ul>
</div>
自定义标签继承自BodyTagSupport,主要是为了获取标签内部生成的页面代码片段。
每个具体的页面都由很多个模块组成,模块就是类似module.jsp的页面,数据通过自定义标签填充
自定义标签的过程:
1. doStartTag到缓存中去取页面片段的代码是否存在,如果存在则直接跳过标签内容的解析;
2. doInitBody通过service层取数据放置到request中供页面片段使用;
3. doEndTag,如果内容为空,则生成页面内容片段,放到缓存中;输出到页面;
感谢下红薯,本文受红薯发在IBM网站上文章的启发!