|
简单的Struts应用开发(2) 第二步: 配置数据库
1.首先创建数据联接bean, 并打包到 ConnectionPool, 它将从我们配置的联接池中取得可用联接.
// Java Document package ConnectionPool; import javax.naming.*; import javax.sql.*; import java.sql.*; import java.io.*; import java.util.*;
public class getDbConnection {
Connection conn; Statement stmt; ResultSet rs=null;
String foo = "Not Connected"; int bar = -1;
public getDbConnection() { try{ Context ctx = new InitialContext(); if(ctx == null ) throw new Exception("Boom - No Context");
DataSource ds = (DataSource)ctx.lookup( "java:comp/env/JDBC/TestDB");
if (ds != null) { conn = ds.getConnection();
} } catch(Exception e) { e.printStackTrace(); } }
public Connection getCon() { return conn; }
public void d_close() throws SQLException { if (rs != null) { try { rs.close(); } catch (SQLException e) { ; } rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { ; } stmt = null; } if (conn != null) { try { conn.close(); } catch (SQLException e) { ; } conn = null; }
}
protected void finalize() throws Throwable { try { d_close(); } catch (SQLException e) { ; } }
}
2.创建数据库.
数据库名: mystruts
部门表: mydep
_______________________________________ dep_id dep_name _______________________________________ 1 dep1 2 dep2 3 dep3 4 dep4 _______________________________________
用户表: myuser ______________________________________________ user_id user_name dep tel ______________________________________________ 1 jack 1 0769-2454042 2 max 2 0769-2454043 ______________________________________________
(注: 以上字段为了测试方便. 全部使用字符型)
第三步: 创建ActionForm (userActionForm.java)
package mystruts; //请打包到mystruts下.
import org.apache.struts.action.*; import javax.Servlet.http.*;
public class userActionForm extends ActionForm { private String action="add"; private String dep; private String tel; private String user_id; private String user_name; public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getDep() { return dep; } public void setDep(String dep) { this.dep = dep; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
return null; } public void reset(ActionMapping actionMapping, HttpServletRequest httpServletRequest) { } } (未完待续)
|