生活随笔
收集整理的這篇文章主要介紹了
使用session保持登录状态,cookie保存用户账号密码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
session保存登錄狀態(tài)與cookie保存賬號密碼
- 1. session維持登錄狀態(tài)
- 2. cookie保存賬號密碼
- 2.1 什么是cookie
- 2.2 cookie記住賬號密碼
1. session維持登錄狀態(tài)
- 利用session的生命周期實(shí)現(xiàn)
1.1 代碼實(shí)現(xiàn)
<form action
="judgeLoginSession" method
="post">name
: <input type
="text" name
="name" /> <br
/>password
:<input type
="password" name
="pwd" /> <br
/><input type
="submit" value
="提交"/></form
>
<%@ page language
="java" import="java.util.*" pageEncoding
="UTF-8"%>
<%
String path
= request
.getContextPath();
String basePath
= request
.getScheme()+"://"+request
.getServerName()+":"+request
.getServerPort()+path
+"/";
%><!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><base href
="<%=basePath%>"><title>My JSP
'index.jsp' starting page
</title
><meta http
-equiv
="pragma" content
="no-cache"><meta http
-equiv
="cache-control" content
="no-cache"><meta http
-equiv
="expires" content
="0"> <meta http
-equiv
="keywords" content
="keyword1,keyword2,keyword3"><meta http
-equiv
="description" content
="This is my page"><script type
="text/javascript">window
.onload
= function() {if ($
{empty name
}) {alert("請登錄!");location
.href
= "login.jsp";}};</script
></head
><body> 歡迎$
{ name
},登錄成功!
</body
>
</html
>
protected void service(HttpServletRequest req
, HttpServletResponse resp
)throws ServletException
, IOException
{String name
= req
.getParameter("name");String pwd
= req
.getParameter("pwd");if ("rye".equals(name
) && "123".equals(pwd
)) {req
.getSession().setAttribute("name", name
);resp
.sendRedirect("index.jsp");} else resp
.sendRedirect("login.jsp");}
- 訪問首頁,js判斷沒有登錄
- 測試
- 登錄成功,跳轉(zhuǎn)首頁
- 關(guān)閉首頁,重新訪問,能取到名字,session存在。
2. cookie保存賬號密碼
2.1 什么是cookie
cookie的基本使用
2.2 cookie記住賬號密碼
<form action
="testCookie" method
="post">name
: <input type
="text" name
="name" value
="${ cookie.name.value }"/> <br
/>password
:<input type
="password" name
="pwd" value
="${ cookie.pwd.value }"/> <br
/>記住密碼
: <input type
="checkbox" name
="remPwd" value
="1"/><input type
="submit" value
="提交"/></form
>
protected void service(HttpServletRequest req
, HttpServletResponse resp
)throws ServletException
, IOException
{String name
= req
.getParameter("name");String pwd
= req
.getParameter("pwd");String remPwd
= req
.getParameter("remPwd");if ("rye".equals(name
) && "123".equals(pwd
)) {if (remPwd
!= null
) { Cookie cookie1
= new Cookie("name", name
);Cookie cookie2
= new Cookie("pwd", pwd
);cookie1
.setMaxAge(60*60);resp
.addCookie(cookie1
);resp
.addCookie(cookie2
);}resp
.sendRedirect("MyJsp.jsp");} else resp
.sendRedirect("login.jsp");}
- 菜鳥f12,cookie如下,服務(wù)器的響應(yīng)如下
我是bitQian,如果你覺得我寫得還闊以,點(diǎn)贊,評論,分享三連擊。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結(jié)
以上是生活随笔為你收集整理的使用session保持登录状态,cookie保存用户账号密码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。