当前位置: 移动技术网 > IT编程>开发语言>Java > JavaWeb使用Cookie模拟实现自动登录功能(不需用户名和密码)

JavaWeb使用Cookie模拟实现自动登录功能(不需用户名和密码)

2019年07月22日  | 移动技术网IT编程  | 我要评论

这里写图片描述

其中包含两个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" "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>
<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" "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 name = request.getparameter("name");
if(name != null && !name.trim().equals("")){
cookie cookie = new cookie("name",name);
cookie.setmaxage(30); //设置cookie有效期为30s
response.addcookie(cookie);
}else{
cookie[] cookies = request.getcookies();
if(cookies != null && cookies.length > 0){
for(cookie cookie:cookies){
string cookiename = cookie.getname();
if("name".equals(cookiename)){
string val = cookie.getvalue();
name = val;
}
}
}
}
if(name != null && !name.trim().equals("")){
out.print("hello: " + name);
}else{//否则重定向到登录界面
response.sendredirect("login.jsp");
}
%>
</body>
</html>

以上所述是小编给大家介绍的javaweb使用cookie模拟实现自动登录功能,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网