一些基础和名词解释
一套用于处理 HTTP 请求的 API 标准。我们可以基于 Servlet 实现 HTTP 请求的处理。
要真正运行 Servlet,需要使用 Servlet Container。 比较常用支持 Servlet Container 的Server 软件有 Apache Tomcat,Glassfish,JBoss,Jetty 等等。
EJB(Enterprise JavaBean)
(不重要,java web中不必须)
一个典型的DAO 模式主要由以下几部分组成。
如:有如下接口ConfigDao和实现该接口的类ConfigDaoImpl:
DAO接口:
public interface PetDao {
/**
* 查询所有宠物 (返回类型是Pet)
*/
List<Pet> findAllPets() throws Exception;
}
DAO实现类:
public class PetDaoImpl implements PetDao {
/**
* 查询所有宠物
*/
public List<Pet> findAllPets() throws Exception {
Connection conn=BaseDao.getConnection();
String sql="select * from pet";
PreparedStatement stmt= conn.prepareStatement(sql);
ResultSet rs= stmt.executeQuery();
List<Pet> petList=new ArrayList<Pet>();
while(rs.next()) {
Pet pet=new Pet(
rs.getInt("id"),
rs.getInt("owner_id"),
rs.getInt("store_id"),
rs.getString("name"),
rs.getString("type_name"),
rs.getInt("health"),
rs.getInt("love"),
rs.getDate("birthday")
);
petList.add(pet);
}
BaseDao.closeAll(conn, stmt, rs);
return petList;
}
}
实体类:
public class Pet {
private Integer id;
private Integer ownerId; //主人ID
private Integer storeId; //商店ID
private String name; //姓名
private String typeName; //类型
private int health; //健康值
private int love; //爱心值
private Date birthday; //生日
}
数据库工具类(连接等功能):
public class BaseDao {
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://127.0.0.1:3306/epet";
private static String user="root";
private static String password="root";
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void closeAll(Connection conn,Statement stmt,ResultSet rs) throws SQLException {
if(rs!=null) {
rs.close();
}
if(stmt!=null) {
stmt.close();
}
if(conn!=null) {
conn.close();
}
}
public int executeSQL(String preparedSql, Object[] param) throws ClassNotFoundException {
Connection conn = null;
PreparedStatement pstmt = null;
/* 处理SQL,执行SQL */
try {
conn = getConnection(); // 得到数据库连接
pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象
if (param != null) {
for (int i = 0; i < param.length; i++) {
pstmt.setObject(i + 1, param[i]); // 为预编译sql设置参数
}
}
ResultSet num = pstmt.executeQuery(); // 执行SQL语句
} catch (SQLException e) {
e.printStackTrace(); // 处理SQLException异常
} finally {
try {
BaseDao.closeAll(conn, pstmt, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
return 0;
}
}
定义的这个接口有啥用啊?是为了别的类似的类可以继承吗?