Java Web 網絡商城案例演示二十一 利用工廠模式解耦(適用於不同數據庫的配置)
通過這種方式只需要配置XML傳入不同的Dao就可以實現不同的DaoImpl連接不同的數據庫
創建XML文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="CategoryDao" class="cn.itzheng.store.dao.daoImpl.CategoryDaoImpl"></bean>
<bean id="UserDao" class="cn.itzheng.store.dao.daoImpl.UserDaoImpl"></bean>
<bean id="ProductDao" class="cn.itzheng.store.dao.daoImpl.ProductDaoImpl"></bean>
</beans>
創建BeanFactory類和createObject方法當中
導入相關架包,用於解析XML
BeanFactory
public class BeanFactory {
public static Object createObject(String name) {
try {
// 通過傳入的類的名稱找到application.xml中name對應是字節碼(class的值)
// class的值通過反射的方式找到器對應的類的實現也就是說通過配置XML文件的方式通過Dao找到DaoImpl,
// 獲取到Document對象
SAXReader reader = new SAXReader();
// 如何獲取application.xml文件的輸入流(application.xml必須位於src下)
InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("application.xml");
// 獲取到該文件對象
Document doc = reader.read(is);
// 解析XML
// 通過Document對象獲取到一個根節點beans
Element rootElement = doc.getRootElement();
// 通過根結點獲取到根結點下所有的子節點bean,返回一個集合
List<Element> list = rootElement.elements();
// 遍歷集合,判斷每個元素上的id的值是否和當前的name一致
for (Element ele : list) {
// ele就相當於beans節點下每個bean
// 獲取到當前節點的id屬性的值
String id = ele.attributeValue("id");
// 如果一致,我們要獲取到當前元素上class屬性的值
if (id.equals(name)) {
String str = ele.attributeValue("class");
// 通過反射創建對象並且返回
Class clazz = Class.forName(str);
return clazz.newInstance();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws SQLException {
UserDao ud = (UserDao) BeanFactory.createObject("UserDao");//通過字節碼獲取到其實現類的對象
User user = new User();
user.setUsername("aaa");
user.setPassword("aaa");
User uu = ud.userLogin(user);//通過接口也就是其父類調用其實力類當中的方法
System.out.println(uu);
}
}
public class CategoryServiceImpl implements CategoryService {
CategoryDao categoryDao = (CategoryDao) BeanFactory.createObject("CategoryDao");
@Override
public List<Category> getAllCats() throws Exception {
return categoryDao.getAllCats();
}
@Override
public void addCategory(Category category) throws Exception {
// 本質是向mysql插入一條數據
categoryDao.addCategory(category);
// 更新redis的緩存
Jedis jedis = JedisUtils.getJedis();// 獲取到Jedis的實例
jedis.del("allCats");// 刪除redis當中對應allCats的數據
JedisUtils.closeJedis(jedis);// 關閉當前jedis對象
// 當訪問頁面時會在CategoryServlet類當中從新開啓redis獲取對應數據庫當中的內容並將其再次放入到redis
}
}
public class UserServiceImpl implements UserService {
UserDao userDao = (UserDao) BeanFactory.createObject("UserDao");
@Override
public void userRegist(User user) throws SQLException {
// TODO Auto-generated method stub
// 實現註冊功能
userDao = new UserDaoImpl();
userDao.userRegist(user);
}
@Override
public boolean userActive(String code) throws SQLException {
// TODO Auto-generated method stub
// 對DB發送select * from user where code = ?
User user = userDao.userActive(code);// 將code傳入到dao層查看數據,返回該code對應的user,以方便後面操作user
if (null != user) {
// 可以根據激活碼查詢到一個用戶
// 修改用戶的狀態,清除激活碼
user.setState(1);
user.setCode(null);
// 對數據庫執行一次真實的更新操作
// update user set username=? ,password = ? ,name = ? ,email = ? ,telephone = ?
// , birthday = ?,sex = ? ,state = ? ,code = ? where uid = ?
userDao.updateUser(user);
return true;
} else {
// 不可以根據激活碼查詢到一個用戶
return false;
}
}
@Override
public User userLogin(User user) throws SQLException {
// 此處:可以利用異常在模塊當中傳遞一些數據
// select * from user where username = ? and password =?
User uu = userDao.userLogin(user);
if (null == uu) {
// 在這裏拋出對應的異常讓其在Servlet裏面捕獲到對應的異常,並反饋到對應的頁面上去
throw new RuntimeException("密碼有誤!");
} else if (uu.getState() == 0) {
throw new RuntimeException("用戶未激活!");
} else {
return uu;
}
}
}
public class ProductServiceImpl implements ProductService {
ProductDao productDao = (ProductDao) BeanFactory.createObject("ProductDao");
@Override
public void saveProduct(Product product) throws Exception {
productDao.saveProduct(product);
}
@Override
public List<Product> findHots() throws Exception {
// TODO Auto-generated method stub
return productDao.findHots();
}
@Override
public List<Product> findNews() throws Exception {
// TODO Auto-generated method stub
return productDao.findNews();
}
@Override
public Product findProductByPid(String pid) throws Exception {
// TODO Auto-generated method stub
return productDao.findProductByPid(pid);
}
// 當點入分類信息的時候,默認cid就是1所以,當前頁得到的就是第1頁,而起始頁經過計算得到的是1終止頁得到的是3
@Override
public PageModel findProductsByCidWithPage(String cid, int curNum) throws Exception {
// 1、創建PageModel對象目的:計算分頁參數
// 統計當前分類下商品的個數 select count(*) from product where cid=?
int totalRecords = productDao.findTotalRecords(cid);
PageModel pm = new PageModel(curNum, totalRecords, 12);
// 2、關聯集合 select * from product where cid = ? LIMIT ?,?
List list = productDao.findProductsByCidWithPage(cid, pm.getStartIndex(), pm.getPageSize());
pm.setList(list);
// 3、關聯url
pm.setUrl("ProductServlet?method=findProductsByCidWithPage&cid=" + cid);
// 返回所有的分頁數據以及對應的頁碼
System.out.println(pm);
return pm;
}
@Override
public PageModel findAllProductsWithPage(int curNum) throws Exception {
// 計算數據庫當中所有商品分類的個數
int totalRecords = productDao.findTotalRecords();
// 1、創建對象
PageModel pm = new PageModel(curNum, totalRecords, 5);
// 2、關聯集合select * from product limit ?,?
List<Product> list = productDao.findAllProductsWithPage(pm.getStartIndex(), pm.getPageSize());
pm.setList(list);
// 3、關聯url
pm.setUrl("AdminProductServlet?method=findAllProductsWithPage");
return pm;
}
}