代码实现的功能
1、假定用户名:系统管理员,密码为123可以登录成功,其他用户拒绝登录,正确实现页面 的跳转和显示
2、在session中保存用户信息并跳转至index.jsp页面中,并在该页面显示用户名,注:需要 对session进行是否为空的判断
index.jsp页面中提供注销按钮,点击注销按钮之后页面跳转至userLogin.jsp登录页面
3、在cookie中保存用户名
4、使用application实现统计登录人数
login.jsp
<% String username1 = ""; Cookie[] cookies = request.getCookies(); for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equals("username")){ username1 = cookies[i].getValue(); } } %> <form action="loginScuess.jsp" method="get"> <p> 用户名:<input value="<%=username1%>" name="username" type="text" id="username"> </p> <p> 密码:<input type="password" name="pwd" value="" id="pwd"> </p> <p> <input value="提交" name="" type="submit"> <input value="重置" name="" type="reset"> </p> </form> <% //String mess = (String)request.getAttribute("mess"); String mess = request.getParameter("info"); if(mess != null){ %> 登录结果:<%=mess%> <% } %>
loginsuccess.jsp
<% String username = request.getParameter("username"); String pwd = request.getParameter("pwd"); //使用转发实现页面跳转 // if(username.equals("admin") && pwd.equals("123")){ // request.setAttribute("mess","欢迎登录!"); // request.getRequestDispatcher("index.jsp").forward(request,response); // }else { // request.setAttribute("mess","您没有权限登录!"); // request.getRequestDispatcher("login.jsp").forward(request,response); // } //使用redirect实现页面跳转 if(username.equals("admin") && pwd.equals("123")){ String info = "登录成功!"; info = URLEncoder.encode(info,"utf-8"); //使用session保存用户信息并跳转至index.jsp session.setAttribute("username",username); //response.sendRedirect("index.jsp?info="+info); //使用cookie保存用户名 Cookie cookie = new Cookie("username",username); cookie.setMaxAge(60*60); cookie.setPath("/"); response.addCookie(cookie); response.sendRedirect("login.jsp"); int count = 0; Object obj = application.getAttribute("count"); if(obj !=null){ count = (int)obj; } if(count == 0){ application.setAttribute("count",1); }else { count++; application.setAttribute("count",count); } }else { String info = "登录失败"; info = URLEncoder.encode(info,"utf-8"); response.sendRedirect("login.jsp?info="+info); } %> 用户名:<%=username%> 密码:<%=pwd%>
首页代码——index.jsp
欢迎登录 <% String username = (String) session.getAttribute("username"); %> 欢迎您!<%=username%> <% int count = 0; Object obj = application.getAttribute("count"); if (obj != null) { count = (int)obj; } %> 在线人数:<%=count%>
注销页代码——loginOut
<% session.invalidate(); int count = 0; Object obj = application.getAttribute("count"); if(obj != null){ count = (int)obj; } count--; application.setAttribute("count",count); response.sendRedirect("login.jsp"); %>