DAO模式是标准的J2EE设计模式之一,典型的DAO实现有下列几个组件:
- 1.DAO工厂类
- 2.DAO接口
- 3.实现DAO接口具体实现类
- 4.数据传递对象
事物划分:transaction demarcation
UserDao:(具体的查询,更新,等方法)
//查询用户激活码
public User findByCode(String code) throw SQLException{
String sql = "select * from t_user where activationCode = ?";
return qr.query(sql,new BeanHandler<User>(User.class),code);
}
//激活用户
public void updateStatus(String uid,boolean status) throws SQLException{
String sql = "update t_user set status=? where uid=?";
qr.update(sql,status,uid);
}
UserService:
public UserDao userDao = new UserDao();
//激活功能
public void activation(String code) throw UserException{
<!--1.通过激活码查询用户-->
<!--2.如果user是null,说明无效是无效激活码,抛异常-->
<!--3.查看用户状态是否为true-->
<!--4.修改状态为true-->
User user = userDao.findByCode(code);
if(user == null)throw new UserException("无效的激活码");
if(user.isStatus()) throw new UserException("您已经激活了,不要二次激活");
userDao.updateStatus(user.getUid(),true);
}
UserServlet:
public String activation(HttpServletRequest req,HttpServletResponse resp) throw ServletException,IOException{
<!--1.获取参数激活码-->
<!--2.用激活码调用service方法完成激活。如果有异常,保存到request中,转发到msg.jsp显示-->
<!--3.保存成功信息到request,转发到msg.jsp显示-->
String code = req.getParameter("activationCode");
try{
userService.activation(code);
req.setAttribute("code","success");
req.setAttribute("msg","恭喜,激活成功");
}catch(UserException e){
req.setAttribute("msg",getMessage());
req.setAttribute("code","error");
}
return "f:/jsps/msg.jsp";
}
创建自己的异常类: 继承Exception,生成构造器 —