文章詳情頁
jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄
瀏覽:529日期:2022-06-08 09:08:29
本文實(shí)例為大家分享了jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄的具體代碼,供大家參考,具體內(nèi)容如下
關(guān)閉瀏覽器只會(huì)使存儲(chǔ)在客戶端瀏覽器內(nèi)存中的session cookie失效,不會(huì)使服務(wù)器端的session對(duì)象失效。
如果設(shè)置了過期時(shí)間,瀏覽器就會(huì)把cookie保存到硬盤上,關(guān)閉后再次打開瀏覽器,這些cookie依然有效直到超過設(shè)定的過期時(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+"\"用戶可自動(dòng)登錄"); %> </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");//獲取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>
運(yùn)行l(wèi)ogin.jsp
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
標(biāo)簽:
JSP
相關(guān)文章:
1. JSP靜態(tài)導(dǎo)入與動(dòng)態(tài)導(dǎo)入使用詳解2. 關(guān)于JSP用戶登錄連接數(shù)據(jù)庫詳情3. JSP簡(jiǎn)明教程:JSP基礎(chǔ)4. 圖解如何在Spring Boot中使用JSP頁面5. JSP之EL表達(dá)式基礎(chǔ)詳解6. JSP實(shí)現(xiàn)分頁效果7. asp+jsp+JavaScript動(dòng)態(tài)實(shí)現(xiàn)添加數(shù)據(jù)行8. vue登錄頁實(shí)現(xiàn)使用cookie記住7天密碼功能的方法9. java和jsp之間的request傳值方法10. PHP如何獲取Cookie并實(shí)現(xiàn)模擬登錄
排行榜
