作者:light
链接:https://www.zhihu.com/question/286739416/answer/454300180
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
链接:https://www.zhihu.com/question/286739416/answer/454300180
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
jsp可以看作一个页面渲染引擎(类比freemark) 那一套页面语法(包含内置对象,页面脚本,el,标签库)最终会被jsp引擎解析为一个servlet类.
在渲染jsp页面的时候 Jsp引擎调用对应的JspTag类(tld文件里关联的)题主所说的useBean 就是在这时候被处理.
具体实现大致像下面这样
- 标签处理类
/*
每当容器解析页面中的每一个 UsebBean时,都会创建一个此类的实例。
*/
public class UsebBean implements SimpleTagSupport{
private String id;
private Class<?> class;
private String scope;
@Override
public void setJspContext(JspContext pc) {
pageContext = (PageContext) pc;
if("request".equals(scope))
pageContext.getRequest().setAttribute(id,)
else if("session".equals(scope))
pageContext.getSession().setAttribute(id,)
else
//省略...
}
//省略其他方法...
}
- tld文件里配置 标签与标签处理类 的对应关系
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<display-name>MyTag Core</display-name> <!-- 标签库名称 -->
<short-name>Light</short-name> <!-- 建议的标签库前缀 -->
<uri>http://www.xx.com/mytag</uri>
<tag>
<name>UsebBean</name>
<tag-class>xx.xx.UsebBean</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>id</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>scope</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>class</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
- jsp页面里使用标签
<%@ taglib prefix="jsp" uri="http://www.xx.com/mytag" %>
<!--
渲染时由jsp引擎创实例化UseBean(通过tld文件找到)并调用setJspContext(),并传入PageCnntext对象
-->
<jsp:UseBean id="jack" scope="request" class="xx.xx.XX">