Request对象: 客户端向服务器发送请求时,服务器对本次请求创建request对象,并在调用Servlet的service方法时,将该对象传递给service方法,Request对象中封装了客户端发来的所有请求数据 —
登陆功能各层实现
1.UserDao
private QueryRunner qr= new TxQueryRunner();
public User findByLoginnameAndLoginpass(String loginname, String loginpass)throw SQLException{
String sql = "select * from t_user where loginname=?and loginpass = ?";
return qr.query(sql,new BeanHandler<User.class>,loginname,loginpass);
}
2.UserService
private UserDao userDao = new UserDao();
public User login(User user){
return userDao.findByLoginnameAndLoginpass(user.getLoginname(),user.getLoginpass());
}
3.UserServlet ``` public String login(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
1.封装表单数据
User formuser = CommonUtils.toBean(req.getParameterMap(),User.class);
2.校验
Map<String,String> errors = validateLogin(formuser,req.getSession());
if(errors.size()>0){
req.setAttribute("form",formUser);
req.setAttribute("errors",errors);
return "f:/jsps/user/login.jsp";
}
3.调用userService#login()方法
User user = userService.login(formuser);
4.开始判断
if(user == null){
req.setAttribute("msg","用户名或者密码错误!");
req.setAttribute("user",formUser);
return "f:/jsps/user/login.jsp";
}else{
if(user.isStatus){
req.setAttribute("msg","你没激活!");
req.setAttribute("user",formUser);
return "f:/jsps/user/login.jsp";
}else{
//保存用户到session
req.getSession.setAttribute("sessionUser",user);
//获取用户名到cookie中
String loginname=user.getLoginname();
loginname = URLEncoder.encode(loginname,"utf-8");
Cookie cookie = new Cookie("loginname",loginname);
cookie.setMaxAge(60*60*24*10);//十天
resp.addCookie(cookie);
return "r:/index.jsp";
}
}
}