login.html
<html>
<head> <title>用户登录</title>
<meta http-equiv="content-type" content="text/html; charset=GBK">
</head>
<body>
<form method="POST" action="loginValidate.jsp">
用户: <input type=text name=username><br>
密码:<input type=password name=password><br><br>
<input type="radio" name="age" value="7"> 将登录信息保存一周 <br>
<input type="radio" name="age" value="30"> 将登录信息保存一个月<br>
<input type="radio" name="age" value="0" checked="checked"> 不保存<br>
<input type=submit value="提交">
<input type=reset vlaue="重置">
</form>
</body>
</html>
loginValidate.jsp
<%@ page pageEncoding="GBK"%>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String age = request.getParameter("age");
int cookieAge = (age==null)? 0: Integer.parseInt(age);
//用户信息验证,这里是简单设定两合法用户,实际中访问有数据库进行验证
if("web".equals(username) && "123456".equals(password) ||
"jsp".equals(username) && "888888".equals(password) )
{
Cookie mycookie = new Cookie("cookie_username",null);//新建
//把登录信息存入Cookie
mycookie.setValue(username);
if(cookieAge!=0) mycookie.setMaxAge(cookieAge*24*3600); //设置最大的存活期,单位为秒
response.addCookie(mycookie);
response.sendRedirect("work.jsp");
}
else{
out.print("<p><b>你没有登录或用户名密码错误!请重新登录!</b><p>");
pageContext.include("login.html");
}
%>
work.jsp
<%@ page pageEncoding="GBK" %>
<%
String username = null;
Cookie c[] = request.getCookies();//读出所有Cookies
if(c!=null){ //存在Cookie
for(int i=0; i < c.length; i++) //遍历所有Cookies,查找需要的Cookie
{
String cookieName = c[i].getName();
if(cookieName.equals("cookie_username")) //找到
username = c[i].getValue(); //取出值
}
}
else{//不存在Cookie,重定向
response.sendRedirect("login.html");
}
if(null==username || 0 == username.length()) //遍历结束后没找到所需的Cookie
response.sendRedirect("login.html"); //转重新登录
else{ //找到所需Cookie
out.print("<p><b>欢迎"+ username + "</b></p>");
out.print("这里是工作页面的内容......");
}
%>