jsp cookie+session实现简易自动登录
本文实例为大家分享了jsp cookie+session实现简易自动登录的具体代码,供大家参考,具体内容如下
关闭浏览器只会使存储在客户端浏览器内存中的session cookie失效,不会使服务器端的session对象失效。
如果设置了过期时间,浏览器就会把cookie保存到硬盘上,关闭后再次打开浏览器,这些cookie依然有效直到超过设定的过期时间。

login.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<head>
<title>登录</title>
</head>
<body>
<form action="sucess.jsp" method="post">
用户名:<input name="username" /><br/>
<%--<input type="checkbox" name="time" />记住用户名 --%>
<input type="submit" name="submit" id="submit" value="登录"/>
</form>
<%
//读取session值
string val= (string)session.getattribute("name");
//如果session不存在
if(val==null){
val ="不存在";
}
out.print("当前\""+val+"\"用户可自动登录");
%>
</body>
</html>
success.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>主不在乎</title>
</head>
<body>
<%
//获取username
string name = request.getparameter("username");
//判断用户名是否存在
if(name != null && !name.trim().equals("")){
//string[] time = request.getparametervalues("time");
//设置session值,(login页面可读取)
session.setattribute("name", name);
//设置cookie
cookie cookie = new cookie("name",name);
cookie.setmaxage(30*24*3600); //设置cookie有效期为30天
response.addcookie(cookie); //在客户端保存cookie
out.println("welcome: " + name+"欢迎登录");
}
else{
response.sendredirect("main.jsp");
}
%>
<a href="login.jsp" >relogin</a>
</body>
</html>
main.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html>
<html>
<head>
<meta charset="iso-8859-1">
<title>主不在乎</title>
</head>
<body>
<%
string name=(string)session.getattribute("username");
//获取cookie
cookie[] cookies = request.getcookies();
//cookie存在
if(cookies != null && cookies.length > 0){
for(cookie cookie:cookies){
//获取cookie的名字
string cookiename = cookie.getname();
//判断是否与name相等
if(cookiename.equals("name")){
//获取cookie的值
string value = cookie.getvalue();
name = value;
}
}
out.println("welcome again: " + name+"欢迎登录");
//*************************
// 另一种写法
string v=null;
for(int i=0;i<cookies.length;i++){
if(cookies[i].getname().equals("name")){
v=cookies[i].getvalue();
}
}
if(v!=null){
out.println(" hello world "+v);
}
}
//*************************
else {
response.sendredirect("login.jsp");
}
%>
<a href="login.jsp" >relogin</a>
</body>
</html>
运行login.jsp

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。


