有几种用法,下面逐一讲解:
1》
<%@page import="MyBean.*"%>
<jsp:useBean class="MyBean.TestBean" id="user" scope="session"/>
生成的java代码如下:
MyBean.TestBean user = null; synchronized (session) { user = (MyBean.TestBean) _jspx_page_context.getAttribute("user", javax.servlet.jsp.PageContext.SESSION_SCOPE); if (user == null){ user = new MyBean.TestBean(); _jspx_page_context.setAttribute("user", user, javax.servlet.jsp.PageContext.SESSION_SCOPE); } }
先从session范围内查找user属性是否存在,如果不存在,user = new MyBean.TestBean(),然后把user追加到session中。存在的话,啥也不做。
2》
<%@page import="MyBean.*"%>
<jsp:useBean type="BaseBean" class="MyBean.TestBean" id="user" scope="session"/>
生成的java代码如下:
BaseBean user = null; synchronized (session) { user = (BaseBean) _jspx_page_context.getAttribute("user", javax.servlet.jsp.PageContext.SESSION_SCOPE); if (user == null){ user = new MyBean.TestBean(); _jspx_page_context.setAttribute("user", user, javax.servlet.jsp.PageContext.SESSION_SCOPE); } }
BaseBean是TestBean的父类。
除了user的类型是BaseBean,其它的处理逻辑和1》相同。
3》
<%@page import="MyBean.*"%>
<jsp:useBean type="MyBean.BaseBean" beanName="MyBean.TestBean" id="user" scope="session"/>
生成的java代码如下:
MyBean.BaseBean user = null; synchronized (session) { user = (MyBean.BaseBean) _jspx_page_context.getAttribute("user", javax.servlet.jsp.PageContext.SESSION_SCOPE); if (user == null){ try { user = (MyBean.BaseBean) java.beans.Beans.instantiate(this.getClass().getClassLoader(), "MyBean.TestBean"); } catch (java.lang.ClassNotFoundException exc) { throw new InstantiationException(exc.getMessage()); } catch (java.lang.Exception exc) { throw new javax.servlet.ServletException("Cannot create bean of class " + "MyBean.TestBean", exc); } _jspx_page_context.setAttribute("user", user, javax.servlet.jsp.PageContext.SESSION_SCOPE); } }
和2》的区别如下: