欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

163-javaweb简单登录与退出

程序员文章站 2022-03-25 09:55:45
...



java简单登录与退出


我们先写Service

public class UserService{

public User login(User form){

//查询username,得到user对象
User user =userDao.findByUsername(form.getUsername());

//如果用户不存在,抛出异常
if(user==null) throw new UserException("用户名不存在");
  
return user;
}



//然后写loing登录方法
public String login(HttpServletRequest request,
		HttpServletResponse response)
		throws ServletException,IOException{
	
	//封装表单数据到form中
	User form=CommonUtils.toBean(request.getParameterMap(),User.class);

	//调用userService的login方法
	try{
	
	User user=userService.login(form);

	//把user保存到session中
	request.getSession().setAttribute("session_user",user);
	
	return "f:/index.jsp";

	}catch(UserException e){
	request.setAttribute("msg",e.getMessage());
	request.setAttribute("form",form);
	return "f:/user/login.jsp";
	}
}

}




public String quit(HttpServletRequest request,
		HttpServletResponse response)
		throws ServletException,IOException{
	request.getSession().invalidate();
	return "f:/index.jsp";
}