欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jsp cookie+session實現(xiàn)簡易自動登錄

 更新時間:2020年10月28日 11:06:47   作者:BADReamer  
這篇文章主要為大家詳細(xì)介紹了jsp cookie+session實現(xiàn)簡易自動登錄,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了jsp cookie+session實現(xiàn)簡易自動登錄的具體代碼,供大家參考,具體內(nèi)容如下

關(guān)閉瀏覽器只會使存儲在客戶端瀏覽器內(nèi)存中的session cookie失效,不會使服務(wù)器端的session對象失效。
如果設(shè)置了過期時間,瀏覽器就會把cookie保存到硬盤上,關(guān)閉后再次打開瀏覽器,這些cookie依然有效直到超過設(shè)定的過期時間。

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("當(dāng)前\""+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");
 
 //設(shè)置session值,(login頁面可讀取)
 session.setAttribute("name", name);
 
 //設(shè)置Cookie
 Cookie Cookie = new Cookie("name",name); 
 Cookie.setMaxAge(30*24*3600); //設(shè)置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>

運行l(wèi)ogin.jsp

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論