Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Unix知識 >> 關於Unix

JSP 入門知識整理:表單、資料庫、檔案與計數器

1. 接收表單參數

String name = new String(request.getParameter("name"));

2. 連接資料庫

以 MySQL 為例,先設定 URL、載入驅動,再建立 Statement 執行 SQL:

String url = "jdbc:mysql://localhost:3306/jspsky";
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
java.sql.Connection connection = java.sql.DriverManager.getConnection(url);
java.sql.Statement statement = connection.createStatement();
java.sql.ResultSet rs = statement.executeQuery(sqlString);
while (rs.next()) {
    String a_name = rs.getString(1);
    out.println(a_name);
}
connection.close();

DB2 的寫法相同,只是驅動與 URL 換掉:

String url = "jdbc:db2:portal";
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
java.sql.Connection connection =
    java.sql.DriverManager.getConnection(url, "user", "password");

別忘了用 try/catch 捕捉 SQLException 與 ClassNotFoundException,並在 finally 中關閉連線,避免連線洩漏。

3. 檔案操作

String hostdir = System.getProperty("user.dir");
String fileBar = System.getProperty("file.separator");
String nameOfFile = hostdir + fileBar + "test.html";

FileOutputStream afile = new FileOutputStream(nameOfFile);
PrintWriter pw = new PrintWriter(afile);
pw.println(str);
pw.close();

用 System.getProperty 取得路徑與分隔符號,比寫死路徑可靠得多。列出目錄內容則是:

String mydir = cdur + fileBar + "doc" + fileBar + "jspsky";
File my = new File(mydir);
String d[] = my.list();
int l = d.length;
for (int i = 0; i < l; i++) { out.print(d[i]); }

4. 簡易計數器

Integer count = null;
synchronized (application) {
    count = (Integer) application.getAttribute("d");
    if (count == null) count = new Integer("0");
    count = new Integer(count.intValue() + 1);
    application.setAttribute("d", count);
}
out.println(count);

做法是先宣告並初始化為 null,從 application 取出屬性轉成整數,為空時給 0,否則加一後再寫回去。synchronized 是必要的一半——沒有它,同時有大量請求時計數會失真。另外,把資料直接串進 SQL 字串有注入風險,正式環境請改用 PreparedStatement 搭配參數綁定。

Copyright © Linux教程網 All Rights Reserved