Cookie免验证自动登录

来源:互联网 发布:mysql导出所有数据库 编辑:程序博客网 时间:2024/05/29 17:31

<!--  Login.jsp  -->

<%@ 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>Insert title here</title>
</head>
<body>

<form action="T_Cookie.jsp">
用户:<input type="text" name="name"/><br><br>
<input type="submit" value="提交">
</form>

</body>
</html>


<!-- Cookie.jsp -->

<%@ 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>Insert title here</title>
</head>
<body>

<%
String name = request.getParameter("name");

//对name 跟 Cookie 进行判断
if(name != null && !name.trim().equals(""))
{
Cookie cookie = new Cookie("name",name);

//20秒生效

cookie.setMaxAge(20);
response.addCookie(cookie);
}else{
Cookie cookies[] = request.getCookies();
if(cookies != null && cookies.length>0)
{
for(Cookie cookie:cookies)
{
String cookie_name = cookie.getName();
if("name".equals(cookie_name))
{
name = cookie.getValue();
}
}
}
}

if(name != null && !name.trim().equals(""))
{
out.print("Hello: "+name);
}else{
response.sendRedirect("T_Login.jsp");
}


%>

</body>
</html>


0 0