session登录练习
登录,判断账号密码跳转到主页面,退出登录,直接访问主页面无法访问
1.登录页面,功能:登录,销毁session
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录</title> </head> <body> 请登录 <% //退出销毁session session.invalidate(); %> <%--跳转到判断页面 --%> <form action="testpw0628.jsp" method="post"> <table> <tr> <td>用户名:</td> <td><input type="text" name="username"/></td> </tr> <tr> <td>密 码:</td> <td><input type="password" name="password"/></td> </tr> <tr> <td><input type="submit" value="登录"/></td> </tr> </table> </form> </body> </html>
2.判断账号,正确跳转主页
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>验证信息</title> </head> <body> <% String username=request.getParameter("username"); String password=request.getParameter("password"); if(username!=""&&password!="") { if(username.equals("test")&&password.equals("4321")) { //设置session session.setAttribute("username",username); //跳转到主页面 response.sendRedirect("main0628.jsp"); } else { out.print("用户名或密码错误!"); } %> <%}else{ out.print("用户名和密码不能为空"); } %> </body> </html>
3.主页,账号密码正确可访问,直接访问提示回话超时,可以退出登录
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>主页</title> </head> <body> <% //检查session Object obj=session.getAttribute("username"); if(obj!=null) { out.print(obj.toString()+",欢迎回来。"); } else { out.print("回话超时,请重新登录"); response.setHeader("refresh", "5;login0628.jsp"); } %> 主页 <br> <a href="login0628.jsp">退出登录</a> </body> </html>