解決JSP中使用request亂碼問題(2)_JSP教程
推薦:JSP環(huán)境配置TOMCAT的內(nèi)存和連接數(shù)配置詳解AJAX jsp無刷新驗(yàn)證碼實(shí)例 如果是使用的catalina.sh(linux)或Catalina.bat(win)啟動(dòng)的: 修改這兩個(gè)文件,加上下面這句: SET CATALINA_OPTS= -Xms64m -Xmx128m 如果使用的wi
(二)數(shù)據(jù)庫處理的雙字節(jié)文字
另外一個(gè),就是寫入數(shù)據(jù)庫的問題,我們知道我們?cè)谑褂胢ysql的時(shí)候可以改用這樣的url來處理漢字編碼問題:jdbc:mysql://localhost:3306/upas?useUnicode=true&characterEncoding=gb2312,那么對(duì)于那些我們無法像mysql這樣解決的怎么辦呢?難道我們每次都這樣寫嗎:
| import java.sql.*; Class.forName("org.gjt.mm.mysql.Driver"); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", ""); pstmt = con.prepareStatement("SELECT f3, f4 FROM tbl1 WHERE f1 = ? AND f2 = ?"); pstmt.setString(1, new String(f1.getBytes("GBK"), "ISO-8859-1"); pstmt.setString(2, new String(f2.getBytes("GBK"), "ISO-8859-1"); rs = pstmt.executeQuery(); String f3, f4; while(rs.next()) { f3 = new String(rs.getString(1).getBytes("ISO-8859-1"), "GBK"); f4 = new String(rs.getString(2).getBytes("ISO-8859-1"), "GBK"); } } finally { //close resouces ... } |
其實(shí)我們完全可以這樣寫:
| import java.sql.*; import com.redv.sql.encoding.*; Class.forName("org.gjt.mm.mysql.Driver"); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", ""); //接管數(shù)據(jù)庫連接實(shí)例 boolean coding = true; EncodingConnection codingConnection = new EncodingConnection(con, coding, "ISO-8859-1", "GBK"); //獲得接管后的數(shù)據(jù)庫連接實(shí)例,以后直接使用con已經(jīng)是經(jīng)過EncodingConnection重新包裝過的實(shí)例 con = codingConnection.getConnection(); pstmt = con.prepareStatement("SELECT f3, f4 FROM tbl1 WHERE f1 = ? AND f2 = ?"); pstmt.setString(1, f1); pstmt.setString(2, f2); rs = pstmt.executeQuery(); String f3, f4; while(rs.next()) { f3 = rs.getString(1); f4 = rs.getString(2); } } finally { //close resouces ... } |
看看,怎么樣,我們只需要在獲取數(shù)據(jù)庫連接的地方稍微修改一下,甚至我們可以把它當(dāng)作參數(shù)保存在 properties里面,改變coding的布爾值來設(shè)定是否使用自動(dòng)編碼轉(zhuǎn)換。常常我們可以使用一個(gè)Database類來封裝獲取數(shù)據(jù)庫連接的那段getConnection,以便于我們可以從 javax.sql.DataSource中獲取到數(shù)據(jù)庫連接。這個(gè)時(shí)候我們僅僅需要修改我們的Database類即可,而不用去搜索所有使用了rs.setString(), rs.getString()的地方去加入我們的編碼轉(zhuǎn)換代碼了。
分享:高手為你解讀J2EE開發(fā)過程中的異常處理在java里有3種異常類型: 1. 檢查型異常,這樣的異常繼承于Excetpion,就是在編譯期間需要檢查,如果該異常被throw,那么在該異常所在的method后必須顯示的throws,調(diào)用該method的地方
- jsp response.sendRedirect不跳轉(zhuǎn)的原因分析及解決
- JSP指令元素(page指令/include指令/taglib指令)復(fù)習(xí)整理
- JSP腳本元素和注釋復(fù)習(xí)總結(jié)示例
- JSP FusionCharts Free顯示圖表 具體實(shí)現(xiàn)
- 網(wǎng)頁模板:關(guān)于jsp頁面使用jstl的異常分析
- JSP頁面中文傳遞參數(shù)使用escape編碼
- 基于jsp:included的使用與jsp:param亂碼的解決方法
- Java Web項(xiàng)目中連接Access數(shù)據(jù)庫的配置方法
- JDBC連接Access數(shù)據(jù)庫的幾種方式介紹
- 網(wǎng)站圖片路徑的問題:絕對(duì)路徑/虛擬路徑
- (jsp/html)網(wǎng)頁上嵌入播放器(常用播放器代碼整理)
- jsp下顯示中文文件名及絕對(duì)路徑下的圖片解決方法
- 相關(guān)鏈接:
- 教程說明:
JSP教程-解決JSP中使用request亂碼問題(2)
。