本文主要是介绍Session登录注销案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用Session完成用户登陆和注销(此程序不能运行,缺少主页与登陆页面)
//处理登陆请求
public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//从客户机提取数据String username = request.getParameter("username");String password = request.getParameter("password");//检测用户名和密码在数据库中是否存在List<User> list = DB.getAll();for(User user : list){if(user.getUsername().equals(username) && user.getPassword().equals(password)){//从数据库中找到匹配用户,让用户登陆成功//设置登陆标记 request.getSession().setAttribute("user", user);//登陆后跳转首页response.sendRedirect("/day07/index.jsp");return;}}//否则没有找到就告诉用户密码错误response.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");response.getWriter().write("用户名或密码错误!!");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}
//模拟数据库
class DB{private static List<User> list = new ArrayList();static{list.add(new User("aaa","123"));list.add(new User("bbb","123"));list.add(new User("ccc","123"));list.add(new User("ddd","123"));}public static List getAll(){return list;}
}
public class User{private String username;private String password;public User() {super();// TODO Auto-generated constructor stub}public User(String username, String password) {super();this.username = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}//注销登陆用户
public class LogoutServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//当session传入false后只会从内存中检索有没有session,没有就返回空,不创建。HttpSession session = request.getSession(false);if(session!=null){//移除登陆标记session.removeAttribute("user");}//注销后跳到首页response.sendRedirect("/day07/index.jsp");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}
这篇关于Session登录注销案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!