您的位置:首頁技術文章
文章詳情頁

jsp cookie+session實現簡易自動登錄

瀏覽:465日期:2022-06-08 09:08:29

本文實例為大家分享了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");//獲取cookieCookie[] 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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。

標簽: JSP
相關文章:
国产综合久久一区二区三区