[問題] jsp和資料庫的連結能不能這樣寫呢?

看板java作者 (全新開始)時間15年前 (2010/06/03 00:08), 編輯推噓6(607)
留言13則, 4人參與, 最新討論串1/1
剛才感謝板眾,為了做實驗反而忘記import java.sql,以致於程式起不來 當初實驗的目地是,我想用一個jsp檔定義所有連結MySQL的變數和建立基本連結, 接著再用另一個jsp檔接續存取資料庫,以免程式碼冗長 第一個jsp 做的事大概是︰ 定義變數,例如url user password,然後 Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, user, pass); Statement stmt = con.createStatement(); 第二個jsp include第一個,然後讀取ResultSet rs = stmt.executeQuery(); 再來處理其他雜務 想籍由這個過程減少第一個jsp那段程式碼的重複.... 但現在問題是前後兩個jsp,程式碼合在一起就正常,分開的話第二個程式的 stmt變數就會出問題,但書上不是說include jsp之後,變數也不用重新定義嗎? 那為什麼stmt會 can not be resolved? 是不是我違反了什麼網路使用者存取資料庫的原則? 在java的API找到這些說明,感覺好像跟這問題有關,但我是新手, 還是不太懂他想表達的意思︰ public interface Statement The object used for executing a static SQL statement and returning the results it produces. By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists. 請問還有什麼地方要考慮嗎? 是不是選錯避免程式碼重複的方法了? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.34.60.41

06/03 00:17, , 1F
不知道你進度如何 如果是資料庫我不會用在JSP上
06/03 00:17, 1F

06/03 00:19, , 2F
include file應該會沒問題 include page就 科科
06/03 00:19, 2F

06/03 00:21, , 3F
你的問題不在於變數啦 就是page之間scope的問題吧
06/03 00:21, 3F
請問不和JSP連線是顧慮到安全問題嗎? 另外include的方式就是 <% include file ="XXXX.jsp" %>,可是好像沒用耶.... ※ 編輯: dream1124 來自: 114.34.60.41 (06/03 00:27)

06/03 00:49, , 4F
我的觀點單純就不易維護 當然啦 JSP也可寫METHOD不是嗎XD
06/03 00:49, 4F

06/03 00:52, , 5F
同一個變數還是別跨page啦 程式碼反而很難看
06/03 00:52, 5F

06/03 10:26, , 6F
何不考慮寫在class檔裡面,不會你的JSP Container不吃吧
06/03 10:26, 6F

06/03 14:46, , 7F
為什麼不寫在class裡??
06/03 14:46, 7F

06/03 20:07, , 8F
不知道進度如何 很多人初學還不會XD 所以我都沒提javaBean
06/03 20:07, 8F

06/03 23:09, , 9F
今天讀書有看到這部分 我也打算這麼做 才比較安全
06/03 23:09, 9F

06/03 23:11, , 10F
可是實作還不知道要怎麼安全地傳資料 XD
06/03 23:11, 10F

06/04 03:20, , 11F
沒有比較安全吧 寫法正常 JSP不過也是servletY
06/04 03:20, 11F

06/04 16:34, , 12F
沒有比較安全阿~只是寫成class比較單純罷了
06/04 16:34, 12F

06/05 18:07, , 13F
dao connection pool 又是一個議題了(茶)
06/05 18:07, 13F
文章代碼(AID): #1C1e7oTw (java)