java web中使用cookie記住用戶的賬號(hào)和密碼
畢業(yè)設(shè)計(jì)中需要用到記住賬號(hào)密碼的功能,網(wǎng)上搜到了一個(gè)解決方案,自己稍加改造就是下面的方法。
首先是登錄的頁面,當(dāng)用戶勾選記住密碼,傳遞給controller(我用的SSM框架),后臺(tái)設(shè)置cookie的值,然后下次登錄的時(shí)候就不用再次輸入賬號(hào)和密碼了。
login.jsp的代碼:
<%@page import="org.apache.commons.lang.StringUtils"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="public/nocache.jsp" %> <%@include file="public/header.jsp" %> <!-- 引入相關(guān)的js --> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <style> body{ margin:0px; padding:0px; } .wrapper{ width:100%;height:100%;position:fixed; } .content{ width:100%; height:100%; position:relative; text-align:center; } .login{ width:1050px; height:450px; position:absolute; top:50%; left:50%; margin-top:-225px; margin-left:-525px; } </style> <script type="text/javascript"> window.history.forward(); window.onbeforeunload=function (){ } </script> <%@include file="public/headertop.jsp" %> <!-- 進(jìn)入資源文件 --> <body> <%-- 讀取cookie --%> <% String name = ""; String password = ""; try{ Cookie[] cookies = request.getCookies(); if(cookies!=null){ for(int i = 0;i<cookies.length;i++){ if(cookies[i].getName().equals("cookie_user")){ String values = cookies[i].getValue(); // 如果value字段不為空 if(StringUtils.isNotBlank(values)){ String[] elements = values.split("-"); // 獲取賬戶名或者密碼 if(StringUtils.isNotBlank(elements[0])){ name = elements[0]; } if(StringUtils.isNotBlank(elements[1])){ password = elements[1]; } } } } } }catch(Exception e){ } %> <div class="wrapper" style=""> <div class="content"> <div class="login"> <!-- 主要的內(nèi)容部分開始 --> <div class="easyui-layout" fit="true" border="false"> <div region="west" style="width:550px;text-align:center;" border="false"> <div class="easyui-layout" fit="true" border="false"> <div region="west" border="false" style="width:250px;height:390px;background:url(${pageContext.request.contextPath}/img/banner-jkrzbg.png)"> </div> <div region="center" style="font-family:'微軟雅黑';" border="false"> <p style="position: relative;margin-top:200px;padding-left:20px;"> <span style="font-size:30px;font-weight:800;">汽車維修管理系統(tǒng)</span><br/> <span>Vehicle Maintenance Management System</span> </p> </div> </div> </div> <div region="center" border="false" style="width:520px;height:480px;"> <div class="easyui-layout" fit="true" border="false"> <div region="north" style="height:80px;" border="false"> </div> <div region="west" style="width:90px;position: relative;" border="false"> <img src="${pageContext.request.contextPath}/img/split.png" style="position:absolute;left:0px;top:30px;"/> </div> <div region="center" border="false"> <div class="easyui-panel" title="用戶登錄" iconCls="icon-user" style="text-align: center;width:300px;height:260px;padding-top:50px;"> <form id="ff" method="post"> <div> <input id="account" class="easyui-textbox" name="accountnumber" data-options="iconCls:'icon-man',prompt:'請(qǐng)輸入用戶名'" value="<%=name %>" style="width:240px;height:30px;"> <a id="dd" href="#" title="用戶的賬號(hào)不能為空" class="easyui-tooltip"></a> </div> <div style="margin-top: 20px;"> <input id="passwords" class="easyui-textbox" name="passwords" type="password" data-options="iconCls:'icon-lock',prompt:'請(qǐng)輸入密碼'" value="<%=password %>" style="width:240px;height:30px;"> </div> <div style="margin-top: 10px;" style="text-align:left;" > <span style="float:left;padding-left:30px;font-size:12px;"><input id="flag" name="flag" type="checkbox" value="1" checked="checked" />記住賬號(hào)</span> </div> <div style="clear:both;"></div> <div style="margin-top: 20px;"> <p> <a href="#" id="submitbtn" style="width:80px;height:30px;" class="easyui-linkbutton" iconCls="icon-accept">登錄</a> <a style="margin-left:30px;width:80px;height:30px;" href="#" class="easyui-linkbutton" iconCls="icon-arrow_undo">取消</a> </p> </div> </form> </div> </div> <div region="east" style="width:90px;" border="false"> </div> <div region="south" style="height:0px;" border="false"> </div> </div> </div> </div> <!-- 主要的內(nèi)容部分結(jié)束 --> </div> </div> </div> <script type="text/javascript"> $(function(){ console.log("[汽車維修管理系統(tǒng)\n codeby:pengchan\n email:dntchenpeng@163.com \n csdn:http://blog.csdn.net/w3chhhhhh/]"); // 提交表單 $("#submitbtn").click(function(){ // 判斷是否為空 if($("#account").val()==""){ $.messager.alert('登錄消息提示','用戶的賬號(hào)不能為空','info'); return; } if($("#passwords").val()==""){ $.messager.alert('登錄消息提示','用戶的密碼不能為空','info'); return; } $("#ff").submit(); }); $('#ff').form({ url:"${pageContext.request.contextPath}/users/login.html", success:function(data){ data = JSON.parse(data); try{ if(data.isError){ $.messager.alert('登錄消息提示',data.errorMsg,'info'); }else{ //$.messager.alert("登錄消息提示","登錄成功!",'info'); // 如果成功,就跳轉(zhuǎn)到主頁面 // 這里先判斷是否有歷史請(qǐng)求,如果有就再次訪問之前的頁面 var hisurl = '${hisURL}'; if(hisurl!=null&&hisurl.length>0){ window.location.href="${pageContext.request.contextPath}"+hisurl; }else{ window.location.href="${pageContext.request.contextPath}/index/main.html"; } } }catch(e){ $.messager.alert("登錄消息提示",'服務(wù)器返回異常,請(qǐng)稍后重試!','info'); } }, error:function(error){ $("#ff").form("clear"); } }); }); </script> </body> </html>
后臺(tái)處理的java部分代碼:
package com.javaweb.controller; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.javaweb.entity.Account; import com.javaweb.service.impl.ServiceFactory; import com.javaweb.utils.BaseController; import com.javaweb.views.LoginBean; /** * 用戶信息控制器 * @author cp * */ @Controller @Scope("prototype") @RequestMapping("/users") public class UserInfoController extends BaseController{ private static final Logger logger = LoggerFactory.getLogger(UserInfoController.class); @Autowired private ServiceFactory serviceFactory; /** * 登錄系統(tǒng) * @param request 請(qǐng)求 * @param model model * @param account 賬戶信息 * @return */ @RequestMapping("/login") @ResponseBody public String login(HttpServletRequest request,HttpServletResponse response,Model model,Account account){ logger.info("用戶嘗試登錄:"+JSON.toJSONString(account)); if(account==null){ return responseFail("提交的參數(shù)為空!"); }else{ if(StringUtils.isBlank(account.getAccountnumber())){ return responseFail("用戶的賬號(hào)為空"); } if(StringUtils.isBlank(account.getPasswords())){ return responseFail("用戶的密碼為空"); } LoginBean loginBean = null; loginBean = serviceFactory.getUserValidateService().userislawable(account); if(loginBean==null){ return responseFail("用戶名或者密碼輸入不正確"); }else{// 如果成功 // 把loginbean放到session中 request.getSession().setAttribute("user", loginBean); // 放到cookie中 String flag = request.getParameter("flag"); // 如果需要記住賬戶就存儲(chǔ)賬號(hào)和密碼 if(flag!=null&&flag.equals("1")){ Cookie cookie = new Cookie("cookie_user",loginBean.getAccountnumber()+"-"+loginBean.getPasswords()); cookie.setMaxAge(60*60*24*3);// 保存 response.addCookie(cookie); logger.info("存儲(chǔ)用戶的cookie:"+loginBean.getAccountnumber()+"-"+loginBean.getPasswords()); }else{// 如果沒有要求記住賬戶密碼,就保存賬戶 Cookie cookie = new Cookie("cookie_user", loginBean.getAccountnumber()); cookie.setMaxAge(60*60*24*30); response.addCookie(cookie); logger.info("存儲(chǔ)用戶的cookie:"+loginBean.getAccountnumber()); } // 跳轉(zhuǎn)到主頁 logger.info("用戶:"+loginBean.getAccountnumber()+"成功進(jìn)入系統(tǒng)"); return responseSuccess(loginBean, "登錄成功"); } } } /** * 退出系統(tǒng)登錄 * @param request 請(qǐng)求 * @param model 模型 * @param accountnum 賬戶號(hào) * @return */ @RequestMapping("/{accountnum}/logout.html") public String logout(HttpServletRequest request,Model model,@PathVariable("accountnum") String accountnum){ logger.info("用戶"+accountnum+",退出系統(tǒng)登錄..."); // 設(shè)置session為空 request.getSession().setAttribute("user", null); // 頁面跳轉(zhuǎn) return "login"; } }
運(yùn)行效果:
輸入賬號(hào)密碼登錄后:
退出后重新登錄:
以上所述是小編給大家介紹的java web中使用cookie記住用戶的賬號(hào)和密碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Mybatis的update更新批量與普通解決方式對(duì)比
這篇文章主要為大家介紹了Mybatis的update更新批量與普通解決方式對(duì)比,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04打包部署若依(RuoYi)SpringBoot后端和Vue前端圖文教程
若依是一個(gè)使用Spring Boot作為后端和Vue.js作為前端的全棧應(yīng)用開發(fā)平臺(tái),下面這篇文章主要給大家介紹了關(guān)于打包部署若依(RuoYi)SpringBoot后端和Vue前端的相關(guān)資料,需要的朋友可以參考下2024-05-05java開發(fā)web前端cookie session及token會(huì)話機(jī)制詳解
如果把人體比作一個(gè)web系統(tǒng)的話,cookie、session和token就好像人體的經(jīng)絡(luò)和血管一樣,而web系統(tǒng)中的數(shù)據(jù),就好像人體的血液一樣。血液依靠著血管在人體內(nèi)流動(dòng),就如數(shù)據(jù)根據(jù)cookie和session機(jī)制在web系統(tǒng)中流動(dòng)一樣2021-10-10Java構(gòu)造函數(shù)與普通函數(shù)用法詳解
本篇文章給大家詳細(xì)講述了Java構(gòu)造函數(shù)與普通函數(shù)用法以及相關(guān)知識(shí)點(diǎn),對(duì)此有興趣的朋友可以參考學(xué)習(xí)下。2018-03-03java實(shí)現(xiàn)短地址服務(wù)的方法(附代碼)
大多數(shù)情況下URL太長,字符多,不便于發(fā)布復(fù)制和存儲(chǔ),本文就介紹了通過java實(shí)現(xiàn)短地址服務(wù),減少了許多使用太長URL帶來的不便,需要的朋友可以參考下2015-07-07淺析對(duì)Java關(guān)鍵字final和static的理解
本文主要給大家談?wù)勑【帉?duì)java關(guān)鍵字final和static的理解,本文給大家介紹的較詳細(xì),需要的朋友參考參考下2017-04-04java中重寫equals()方法的同時(shí)要重寫hashcode()方法(詳解)
下面小編就為大家?guī)硪黄猨ava中重寫equals()方法的同時(shí)要重寫hashcode()方法(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05Maven實(shí)戰(zhàn)之搭建Maven私服和鏡像的方法(圖文)
本篇文章主要介紹了搭建Maven私服和鏡像的方法(圖文),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12