初期学javaweb的时候动态输出网页就靠servlet和jsp完成了,后来简单了解了php和python可以通过渲染网页模板完成网页的继承,也在官网上了解了一下jsp模板的继承,在这里分享一下。
jsp继承网页模板只需要两个类就可以简单完成,依赖于rapid-framework-3.9.3.20100923.jar
第一次发表博文,还希望大家多多鼓励~
这个是BlockTag类,主要功能是定义jsp中的模板标签即<jsp:block />
package com.cheney.jspInheritance;
import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; /** * * Project: jspInheritance * Class: BlockTag * : Cheney * @Date 2015年9月8日 下午9:06:36 * 1.0 * */ public class BlockTag extends TagSupport{ private static final long serialVersionUID = -8246166191638588615L; private String name; public void setName(String name) { this.name = name; } /** * EVAL_BODY_INCLUDE or EVAL_BODY_BUFFERED or SKIP_BODY */ @Override public int doStartTag() throws JspException { return getOverriedContent() == null ? EVAL_BODY_INCLUDE : SKIP_BODY; } /** * @return EVAL_PAGE or SKIP_PAGE */ @Override public int doEndTag() throws JspException { String overriedContent = getOverriedContent(); if(overriedContent == null) { return EVAL_PAGE; } try { pageContext.getOut().write(overriedContent); } catch (IOException e) { throw new JspException("write overridedContent occer IOException,block name:"+name,e); } return EVAL_PAGE; } private String getOverriedContent() { String varName = Utils.getOverrideVariableName(name); return (String)pageContext.getRequest().getAttribute(varName); } }下面这个是OverwriteTag 类,主要功能是定义jsp中子页面的继承标签即<jsp:overwrite />
package com.cheney.jspInheritance;
import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTagSupport; import org.apache.commons.lang3.StringUtils; /** * * Project: jspInheritance * Class: OverwriteTag * @author: Cheney * @Date 2015年9月8日 下午9:12:04 * @version 1.0 * */ public class OverwriteTag extends BodyTagSupport { private static final long serialVersionUID = -8379959647039117369L; private String name; public void setName(String name) { this.name = name; } @Override public int doStartTag() throws JspException { return isOverrided() ? SKIP_BODY : EVAL_BODY_BUFFERED; } @Override public int doEndTag() throws JspException { if(isOverrided()) { return EVAL_PAGE; } BodyContent b = getBodyContent(); // System.out.println("Override.content:"+b.getString()); String varName = Utils.getOverrideVariableName(name); pageContext.getRequest().setAttribute(varName, b.getString()); return EVAL_PAGE; } private boolean isOverrided() { String varName = Utils.getOverrideVariableName(name); return pageContext.getRequest().getAttribute(varName) != null; } }下面这个是一个工具类,作用是定义标签的格式
package com.cheney.jspInheritance;
/** * * Project: jspInheritance * Class: Utils * @author: Cheney * @Date 2015年9月10日 下午8:46:53 * @version 1.0 * */ class Utils { public static String BLOCK = "__jsp_override__"; static String getOverrideVariableName(String name) { return BLOCK + name; } }这样的话jsp的模板继承功能就实现了~