1. 程式人生 > >java使用cookies儲存使用者登入資訊

java使用cookies儲存使用者登入資訊

一.本程式要實現的功能
第一次登入頁面時,若在表單中選擇了“記住密碼”,則下次登入網站時不用在填寫表單,這裡用“success.jsp”表示要開啟的頁面。若本地Cookie檔案中已經儲存了驗證資訊,則會顯示已登入,否則會顯示沒登入。
具體如下所示:
① .填寫表單,選擇記住密碼“一天“,程式碼檔案為:login.jsp

② .按下提交後,客戶鍛頁面跳到check.jsp,實際上在服務端已經跳到了“success.jsp”頁面。

③ .新開啟一個瀏覽器,然後直接開啟“success.jsp”頁面,此時提示已登入。說明Cookie起到了自動登入的作用。

若第①步中,在記住密碼項中選擇“不儲存”則登入“success.jsp”頁面
二. 對應程式碼
login.jsp

[java] view plaincopy
<%@ page contentType="text/html;charset=GBK"%>
<mce:script language="javaScript"><!--
function validate(f){
if(!(/^/w{5,15}$/.test(f.userId.value))){
alert("使用者id必須為5-15位!");
f.userId.focus();
return false;
}
if(!(/^/w{5,15}$/.test(f.password.value))){
alert("密碼必須為5-15位!");
f.password.focus();
return false;
}
return true;
}
// --></mce:script>
<form action="check.jsp" method="post" onSubmit="return validate(this)">
<table border="0">
<tr>
<td>登入程式</td>
</tr>
<tr>
<td>
使用者id:
</td>
<td>
<input type="text" name="userid">
</td>
</tr>
<tr>
<td>
密 碼:
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>
記住密碼?
</td>
<td>
<select name="savetime">
<option value="0" selected>不儲存</option>
<option value=<%=24*60*60%>>一天</option>
<option value=<%=24*60*60*7%>>一週</option>
</select>
</td>
</tr>
<tr>
<td> <input type="submit" value="確認"></td>
<td> <input type="reset" value="重置"></td>
</tr>
</table>
</form>

check.jsp

[c-sharp] view plaincopy
<%@ page import="java.sql.*"%>
<%!
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
public static final String DBURL = "jdbc:mysql://localhost:3306/jspDemo" ;
public static final String DBUSER = "root" ;
public static final String DBPASS = "root" ;
%>
<%
Connection conn = null ;
PreparedStatement pstmt = null ;
ResultSet rs = null ;
boolean flag = false ; // 表示登陸成功或失敗的標記
%>
<%
String userid = request.getParameter("userid") ; // 接收表單引數
String password = request.getParameter("password") ; // 接收表單引數
String savetime=request.getParameter("savetime");
System.out.println(savetime);
try{
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
String sql = "SELECT id FROM tuser WHERE id=? AND password=?" ;
pstmt = conn.prepareStatement(sql) ;
pstmt.setString(1,userid) ;
pstmt.setString(2,password) ;
rs = pstmt.executeQuery() ;
if(rs.next()){
// 如果有內容,則此處執行,表示查詢出來,合法使用者
flag = true ;
session.setAttribute("userid",userid);
//將驗證資訊儲存到Cookie
Cookie cid=new Cookie("userid",userid);
Cookie cpass=new Cookie("password",password);
cid.setMaxAge(Integer.parseInt(savetime));
cpass.setMaxAge(Integer.parseInt(savetime));
response.addCookie(cid);
response.addCookie(cpass);
}
}catch(Exception e){
}finally{
try{
conn.close() ; // 連線一關閉,所有的操作都將關閉
}catch(Exception e){
e.printStackTrace();
}
}
%>
<%
if(flag){ // 登陸成功,應該跳轉到success.jsp
%>
<jsp:forward page="success.jsp"/>
<%
}else{ // 登陸失敗,跳轉到failure.jsp
%>
<jsp:forward page="failure.jsp"/>
<%
}
%>

CookieCheck.jsp

[java] view plaincopy
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="java.sql.*"%>
<%!
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
public static final String DBURL = "jdbc:mysql://localhost:3306/jspDemo" ;
public static final String DBUSER = "root" ;
public static final String DBPASS = "root" ;
%>
<%
Connection conn = null ;
PreparedStatement pstmt = null ;
ResultSet rs = null ;
boolean flag = false ; // 表示登陸成功或失敗的標記
%>
<%
if(session.getAttribute("userid")==null){
Cookie[] c=request.getCookies();
String userid=null;
String password=null;
if(c!=null){
for(int i=0;i<c.length;i++){
if("userid".equals(c[i].getName())){
userid = c[i].getValue() ; // 接收Cookie資訊
}
if("password".equals(c[i].getName())){
password = c[i].getValue() ; // 接收Cookie資訊
}
}
if(userid!=null&&password!=null){
try{
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
String sql = "SELECT id FROM tuser WHERE id=? AND password=?" ;
pstmt = conn.prepareStatement(sql) ;
pstmt.setString(1,userid) ;
pstmt.setString(2,password) ;
rs = pstmt.executeQuery() ;
if(rs.next()){
// 如果有內容,則此處執行,表示查詢出來,合法使用者
flag = true ;
session.setAttribute("userid",userid);
}
}catch(Exception e){
}finally{
try{
conn.close() ; // 連線一關閉,所有的操作都將關閉
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
%>

succss.jsp

[java] view plaincopy
<%@ page contentType="text/html;charset=GBK"%>
<jsp:include page="CookieCheck.jsp"/>
<%
if(session.getAttribute("userid")!=null){
%>
<h1>登陸成功,歡迎光臨!</h1>
<%
}else{
%>
<h1> 您還未登入!</h1>
<%
}
%>

failue.jsp

[xhtml] view plaincopy
<%@ page contentType="text/html;charset=GBK"%>
<h1>登陸失敗,請重新<a href="login.html" mce_href="login.html">登陸</a></h1>

相關推薦

vue專案使用localStorage+Vuex來儲存使用者登入資訊

api.js import axios from 'axios' const baseURL = 'http://XXX // 全域性的 axios 預設值 axios.defaults.baseUR

java使用cookies儲存使用者登入資訊

一.本程式要實現的功能第一次登入頁面時,若在表單中選擇了“記住密碼”,則下次登入網站時不用在填寫表單,這裡用“success.jsp”表示要開啟的頁面。若本地Cookie檔案中已經儲存了驗證資訊,則會顯示已登入,否則會顯示沒登入。具體如下所示:① .填寫表單,選擇記住密

米絡科技學習網站的測試網站突然登入不了,由於session沒有儲存登入資訊

session資訊儲存在memcache 裡,重啟下memcache, 過程: 1測試是否成功安裝memcached: ls -al /usr/local/bin/mem* 2.啟動memcached /usr/local/bin/memcached -d -m 10 -u ro

javaweb 登入驗證儲存登入資訊

使用的Strust2框架,寫了一個過濾器LoginFilter但在跳轉頁面後發現s標籤中的登入Action內容沒有正常顯示因為直接跳轉的話少了一句     this.user = this.userManager.loadByEmail(user.getEmail(

vue使用localStorage儲存登入資訊,適用於移動端、pc端

眾所周知,vue可以用來開發移動端app,可以使用hbuilder將build好的vue打包成一個移動端app,但是用過之後就會發現,使用cookies或者session儲存登入的token,在手機端無

通過cookie儲存並讀取使用者登入資訊例項

通過cookie的getCookies()方法可獲取所有cookie物件的集合;通過getName()方法可以獲取指定的名稱的cookie;通過getValue()方法獲取到cookie物件的值。另外,將一個cookie物件傳送到客戶端,使用response物件的addCo

【android-Webview】設定多個cookie,實現webview中儲存登入資訊

方法:通過重複呼叫 cookieManager.setCookie(url,cookie1); 來儲存多個cookie。 程式碼: /** * Sync Cookie */ private void syncCookie(Context

C++通過檔案讀寫儲存使用者註冊登入資訊

        我的MySQL因為電腦的反覆重灌實在是裝不好了,不知道少解除安裝了什麼導致MySQL裝不好。那麼我就自己寫一個檔案來儲存使用者名稱和密碼這兩個登入資訊吧。整體上用到了檔案的讀寫操作。        我用到了兩個函式,分別是int regest()和int lo

Session 使用者儲存登入資訊

.com',     'sex'  => 'man',     'age'  => '18' ); header("content-type:text/html; charset=utf-8"); /* 將使用者資訊儲存到session中 */ $_SESSION['uid'] = $userin

通過Cookie儲存並讀取使用者登入資訊

 1:設定Cookie <%@ page contentType=" text/html;charset=UTF-8" language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ pag

cookie中儲存登入資訊的基本操作

import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import

Mac下,使用sshpass讓iterm2支援多ssh登入資訊儲存

解壓到當前資料夾 tar -zxvf sshpass-版本號.tar.gz解壓後進入sshpass目錄,終端執行以下命令 ​ ./configure ​ make ​ ins

利用sharedPreference來儲存我們的登入資訊

今天大週六的,還要在家辦公繼續寫我們的app。 隨便抱怨兩句,為廣大的程式設計師無病呻吟兩下。 那麼開始今天的正片環節吧,沒什麼技術含量,本人也是一隻小菜雞,慢慢進步嘛。 對sharedPreference下面都用簡稱sp了。 我們利用sp來對app的登入資訊進行儲存,然後

07-通過cookie儲存並讀取使用者登入資訊(jsp內建物件)

cookie.jsp <%@page import="java.net.URLDecoder"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <ht

php curl儲存登入資訊 模擬登入

在模擬論壇登入的時候,伺服器上會生成一個cookie 這個時候需要把cookie儲存,再每次請求的時候帶上這個cookie就可以

Python3 Post登入並且儲存cookie登入其他頁面

import urllib.request import sys import http.cookiejar import urllib.parse from bs4 import BeautifulSoup import codecs import re #登入頁面 url = "h

Google儲存海量私人資訊 隱私問題不堪設想

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

使用filter進行登入的攔截,統一驗證使用者登入資訊是否有效

1需求 在使用者進行所有的操作之前都要驗證當前使用者是否登入有效,如果每個方法呼叫前都去驗證顯得比較蠢,於是使用filter在介面之前統一攔截驗證; 2.方案的選擇 簡單的來說就是實現使用者的登入。剛開始我是採用session和cookie進行使用者登入的,可是涉及到跨域的問題。其實我在

PHP表單驗證+Session來儲存表單資訊

剛入門PHP,簡單的練習,判斷使用者名稱、密碼不能為空,提交後儲存在session中 <!DOCTYPE HTML> <?php session_start(); //啟動會話 ?> <html> <head> <style&g

批量儲存一條資訊

// 閘道器儲存     @RequestMapping(value = "/gatewayUpdate/{roomid}", method = RequestMethod.POST)     @ResponseBody  &nb