因为项目迭代 所以项目复用是必须的 idea 拷贝项目
项目梗概
- 在crm/customer/list 下面显示
- list.jsp跳转add.html 进行save操作
- crm/customer/save
添加Artifacts
对于新创建项目如果未出现 可以在这里进行删除 添加
如果全部删掉
可以进行添加
修改Application context:
资源文件
jar->WEB-INF->lib中
创建lib文件夹 复制jar进去
resources
将阿里巴巴的druid资源文件复制到resources下面
编译一波
Dbs工具类
- 读取配置 注册mysql驱动 DriverManager 或 获取 Datasource(druid)
- 不涉及bean层,dao层
设计一个update功能
要求
- 传入一个sql语句和多个obj用于完善
PreparedStatement - 返回值int(利用executexx返回值即可)
Dao层呢?
public static boolean save(Customer customer) {
//String sql = "INSERT INTO customer (name,phone) VALUES ('王盼盼','13505613657');";
String sql = "INSERT INTO customer (name,phone) VALUES (?,?);";
return Dbs.update(sql,customer.getName(),customer.getPhone()) > 0 ? true : false;
}
Dbs层
public static int update(String sql,Object... args) {
try {
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql);
int index = 1;
for (Object arg : args) {
statement.setObject(index,args[index -1]);
index++;
}
System.out.println(statement.toString());
return statement.executeUpdate();
} catch (Exception e) {
return 0;
}
}
测试
Customer customer = new Customer();
customer.setName("赵小米1");
customer.setPhone("16666666666");
System.out.println(CustomerDao.save(customer) ? "插入成功" : "插入失败");
设计一个query功能
- 返回范型 总不能把bean层传入吧
- 其余类似update功能 Dao层
public static List<Customer> list() {
//SELECT name,phone FROM customer WHERE `name` LIKE '王%';
String sql = "SELECT id,name,phone,company_id FROM customer WHERE `name` LIKE ?;";
List<Customer> list = Dbs.query(sql,(rs, row) -> {
Customer customer = new Customer();
customer.setId(Integer.valueOf(rs.getInt("id")));
customer.setName(rs.getString("name"));
customer.setPhone(rs.getString("phone"));
customer.setCompany_id(Integer.valueOf(rs.getInt("company_id")));
return customer;
},"王%");
/**
* Dbs.query(sql, new Dbs.RowMapper<Customer>() {
* @Override
* public Customer map(ResultSet rs, int row) throws Exception {
* return null;
* }
* },"王%");
*/
return list;
}
Dds层
public static <T> List<T> query(String sql, RowMapper<T> mapper,Object... args) {
try {
Connection connection = dataSource.getConnection();
try (PreparedStatement statement = connection.prepareStatement(sql);){
int index = 1;
for (Object arg : args) {
statement.setObject(index,args[index -1]);
index++;
}
System.out.println(statement.toString());
List<T> list = new ArrayList<>();
try (ResultSet resultSet = statement.executeQuery();){
for (int row = 0; resultSet.next(); row++) {
list.add(mapper.map(resultSet,row));
}
}
return list;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public interface RowMapper<T> {
T map(ResultSet rs, int row) throws Exception;
}
测试
List<Customer> list = CustomerDao.list();
for (Customer customer : list) {
System.out.println(customer);
}
创建servlet 实现多路径
@WebServlet("/customer/*")
做映射