JavaWeb使⽤Cookie模拟实现⾃动登录功能(不需⽤户名
和密码)
其中包含两个jsp⽂件,分别为login.jsp和index.jsp
代码如下:
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录界⾯</title>
</head>
<body>
<form action="index.jsp" method="post">
⽤户名:<input type="text" name="name"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>欢迎您</title>
</head>
<body>
<%
String name = Parameter("name");
if(name != null && !im().equals("")){
Cookie cookie = new Cookie("name",name);
cookie.setMaxAge(30); //设置cookie有效期为30s
response.addCookie(cookie);
}else{
Cookie[] cookies = Cookies();
if(cookies != null && cookies.length > 0){
用户登录界面设计代码htmlfor(Cookie cookie:cookies){
String cookieName = Name();
if("name".equals(cookieName)){
String val = Value();
name = val;
}
}
}
}
if(name != null && !im().equals("")){
out.print("hello: " + name);
}else{//否则重定向到登录界⾯
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
以上所述是⼩编给⼤家介绍的JavaWeb使⽤Cookie模拟实现⾃动登录功能,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!