這是一個困擾我很久的問題了,一直不明白<jsp:useBean>在jsp文件轉為servlet時是怎樣編譯的,今天找到答案了,高興,呵呵,請看:
JSP中正確應用類:
應該把類當成JAVA BEAN來用,不要在<% %> 中直接使用. 如下的代碼(1)經過JSP引擎轉化后會變為代碼(2):
從中可看出如果把一個類在JSP當成JAVA BEAN 使用,JSP會根據它的作用范圍把它保存到相應的內部對象中.
如作用范圍為request,則把它保存到request對象中.并且只在第一次調用(對象的值為null)它時進行實例化. 而如果在<% %>中直接創建該類的一個對象,則每次調用JSP時,都要重新創建該對象,會影響性能.
代碼(1)
<jsp:useBean id="test" scope="request" class="demo.com.testdemo">
</jsp:useBean>
<%
test.print("this is use java bean");
testdemo td= new testdemo();
td.print("this is use new");
%>
代碼 (2)
demo.com.testdemo test = (demo.com.testdemo)request.getAttribute("test");
if (test == null)
{
try
{
test = (demo.com.testdemo) java.beans.Beans.instantiate(getClass().getClassLoader(),"demo.com.testdemo");
}
catch (Exception _beanException)
{
throw new weblogic.utils.NestedRuntimeException("cannot instantiate 'demo.com.testdemo'",_beanException);
}
request.setAttribute("test", test);
out.print("\r\n");
}
out.print("\r\n\r\n\r\n");
test.print("this is use java bean");
testdemo td= new testdemo();
td.print("this is use new");
原來指定作用范圍是這么一回事