jsp調用javeabean命令usebean中有scope設置,一般有application session page等設置,page就是每頁重新產生usebean中的javabean新對象,一般情況是用這種,如果多個jsp程序間為共享數據,可以使用session
而application的意思,該javabean將一直存在,與session相對用戶來說,application是相對應用程序的,一般來說,一個用戶有一個session,并且隨著用戶離開而消失;而application則是一直存在,類似一個servlet程序,類似整個系統的"全局變量",而且只有一個實例。
mvc中控制功能
因此application這個特性,很適合用來做mvc中的控制功能,一般傳統mvc是用servlet做控制功能,v基本是jsp頁面,m就是中間件javabean之類。
但是隨著jsp功能的完善和推廣,逐漸有替代servlet之趨勢,我們在實踐中更多使用的也是jsp,有時為了省卻麻煩的事情,就使用jsp代替servlet.尤其是其控制功能。
實際上,這個控制功能是封裝在一個javabean中,jsp使用scope=application來調用這個javabean,這樣,具備控制功能的javabean就類似servlet常駐內存,并和后臺各種中間件交互操作。
“首頁”的展現
在實際應用中,我們經常有多個用戶要同時訪問一個頁面,如首頁,這個首頁中有很多功能要運行,比如目錄分類,首頁程序要從數據庫中讀入樹形數據并展開,輸出到首頁,這個功能是封裝在javabean中的。
那么首頁jsp調用這個javabean時,使用scope=application, 再通過樹形數據的緩沖算法,這樣,多個用戶同時訪問首頁時,首頁jsp就無需每次啟動javabean然后再反復讀取數據庫了。無疑大大提高速度。
所以如果你的首頁jsp訪問量很高,那么就應該在這方面多花點時間優化。
數據庫連接緩沖
<jsp:usebean id="cods"
class="oracle.jdbc.pool.oracleconnectioncacheimpl"
scope="application" />
<event:application_onstart>
<%
cods.seturl("jdbc:oracle:thin:@host:port:sid");
cods.setuser("scott");
cods.setpassword("tiger");
cods.setstmtcache (5);
%>
</event:application_onstart>
<%@ page import="java.sql.*, javax.sql.*, oracle.jdbc.pool.*" %>
<!----------------------------------------------------------------
* this is a javaserver page that uses connection caching over
application
* scope. the cache is created in an application scope in
globals.jsa file.
* connection is obtained from the cache and recycled back once
done.
--------------------------------------------------------------------!>
<html>
<head>
<title>
conncache jsp
</title>
</head>
<body bgcolor=eofffo>
<h1> hello
<%= (request.getremoteuser() != null? ", " +
request.getremoteuser() : "") %>
! i am connection caching jsp.
</h1>
<hr>
<b> i get the connection from the cache and recycle it back.
</b>
<p>
<%
try {
connection conn = cods.getconnection();
statement stmt = conn.createstatement ();
resultset rset = stmt.executequery ("select ename, sal " +
"from scott.emp order by ename");
if (rset.next()) {
%>
<table border=1 bgcolor="c0c0c0">
<th width=200 bgcolor="white"> <i>employee name</i> </th>
<th width=100 bgcolor="white"> <i>salary</i> </th>
<tr> <td align=center> <%= rset.getstring(1) %> </td>
<td align=center> $<%= rset.getdouble(2) %> </td>
</tr>
<% while (rset.next()) {
%>
<tr> <td align=center> <%= rset.getstring(1) %> </td>
<td align=center> $<%= rset.getdouble(2) %> </td>
</tr>
<% }
%>
</table>
<% }
else {
%>
<p> sorry, the query returned no rows! </p>
<%
}
rset.close();
stmt.close();
conn.close(); // put the connection back into the pool
} catch (sqlexception e) {
out.println("<p>" + "there was an error doing the query:");
out.println ("<pre>" + e + "</pre>
<p>");
}
%>
</body>
</html>
使用application緩存數據庫的連接,每次使用時,從緩沖中取出,用完就返回。
新聞熱點
疑難解答