直接上代码:
01 |
public class IncludeTag extends BodyTagSupport
{ |
03 |
private static final long serialVersionUID
= 3048295381656105593L; |
04 |
private final String
CACHENAME = "TAG_CACHE" ; |
05 |
private String
content; |
08 |
public int doStartTag() throws JspException
{ |
09 |
content
= (String)CacheHelper.get(CACHENAME); |
13 |
return super .doStartTag(); |
17 |
public void doInitBody() throws JspException
{ |
20 |
pageContext.getRequest().setAttribute( "key" , "value" ); |
21 |
List<String>
lst = new ArrayList<String>(); |
24 |
pageContext.getRequest().setAttribute( "list" ,
lst); |
29 |
public int doAfterBody() throws JspException
{ |
30 |
return super .doAfterBody(); |
34 |
public int doEndTag() throws JspException
{ |
36 |
content
= bodyContent.getString().trim(); |
37 |
if (content.length()
!= 0 ||
!content.equalsIgnoreCase( "null" ))
{ |
38 |
CacheHelper.set(CACHENAME,
content); |
43 |
pageContext.getResponse().getWriter().print(content); |
44 |
} catch (IOException
e) { |
48 |
return super .doEndTag(); |
调用自定义标签的页面:
01 |
<%@
page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> |
02 |
<%@
taglib prefix="my" uri="/WEB-INF/my.tld" %> |
03 |
<!DOCTYPE
html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> |
06 |
< meta http-equiv = "Content-Type" content = "text/html;
charset=UTF-8" > |
10 |
<%@
include file="include.jsp" %> |
module.jsp页面的内容:
01 |
<%@
page import="java.util.*" %> |
02 |
<%=request.getAttribute("key")
%> |
06 |
List
lst = (List)request.getAttribute("list"); |
07 |
for(int
i=0; i< lst.size ();
i++) { |
09 |
< li ><%=lst.get(i)
%></ li > |
自定义标签继承自BodyTagSupport,主要是为了获取标签内部生成的页面代码片段。
每个具体的页面都由很多个模块组成,模块就是类似module.jsp的页面,数据通过自定义标签填充
自定义标签的过程:
1. doStartTag到缓存中去取页面片段的代码是否存在,如果存在则直接跳过标签内容的解析;
2. doInitBody通过service层取数据放置到request中供页面片段使用;
3.
doEndTag,如果内容为空,则生成页面内容片段,放到缓存中;输出到页面;