一、什么是jsp封装
jsp封装就是把我们写在jsp中的java代码封装出去,用专门的类来定义方法,然后再jsp中调用此方法,以此来实现我们的功能,是我们看得更加方便,整洁。
二、封装步骤
1、首先先建三个包,分别为:entity实体类,dao类和untilDBHelper类
2、首先就是我们的util类,写我们DBHelper类也就是我们的连接数据库。
DBHelper是我们连接oracle数据库的代码
源代码展示:
package com.zking.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBHelper {
private static String user="scott";
private static String password="1234";
private static String cname="oracle.jdbc.driver.OracleDriver";
private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
//注册驱动类
static {
try {
Class.forName(cname);
} catch (Exception e) {
e.printStackTrace();
}
}
//连接数据库
public static Connection getCon() {
Connection con=null;
try {
con=DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
//关闭连接
public static void ColseDb(Connection con,PreparedStatement ps,ResultSet rs) {
try {
if(con!=null) {
con.close();
}
if(ps!=null) {
ps.close();
}
if(rs!=null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下一个获取下一个编号的方法
* @return 下一个编号
*/
public static int getNextId(String tableName,String col) {
int id = 1;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBHelper.getCon();
ps = con.prepareStatement("select max("+col+") from "+tableName);
rs = ps.executeQuery();
if(rs.next()) {
id = rs.getInt(1)+1;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.ColseDb(con, ps, rs);
}
return id;
}
}
ps:其中有有一个获取下一个编号的方法,这个就是在我们添加数据时因为oracle没有主键自增的功能,所有我们在这里写了一个方法首先找到最大的编号,然后再最大编号的基础加一,成为我们要添加的数据的编号。
3、其次是实体类(先写属性,然后创建get和set方法还有构造函数)
ps:这个是实现我们的
4、第三个就是我们的dao类,在dao类中我们需要写我们要实现的功能的方法。