java web中使用cookie記住用戶的賬號(hào)和密碼
畢業(yè)設(shè)計(jì)中需要用到記住賬號(hào)密碼的功能,網(wǎng)上搜到了一個(gè)解決方案,自己稍加改造就是下面的方法。
首先是登錄的頁(yè)面,當(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)到主頁(yè)面
// 這里先判斷是否有歷史請(qǐng)求,如果有就再次訪問之前的頁(yè)面
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)到主頁(yè)
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);
// 頁(yè)面跳轉(zhuǎn)
return "login";
}
}
運(yùn)行效果:

輸入賬號(hào)密碼登錄后:

退出后重新登錄:

以上所述是小編給大家介紹的java web中使用cookie記住用戶的賬號(hào)和密碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
詳解配置spring-boot-actuator時(shí)候遇到的一些小問題
這篇文章主要介紹了詳解配置spring-boot-actuator時(shí)候遇到的一些小問題,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
Java多線程實(shí)現(xiàn)Callable接口
本文給大家分享的是使用Java多線程來(lái)實(shí)現(xiàn)callable接口的方法,以及使用方法,另外還有一個(gè)網(wǎng)友的實(shí)例,希望能夠?qū)Υ蠹艺莆認(rèn)ava多線程有所幫助。2016-06-06
Java實(shí)現(xiàn)對(duì)字符串中的數(shù)值進(jìn)行排序操作示例
這篇文章主要介紹了Java實(shí)現(xiàn)對(duì)字符串中的數(shù)值進(jìn)行排序操作,涉及java字符串與數(shù)組的相互轉(zhuǎn)換以及數(shù)組排序相關(guān)操作技巧,需要的朋友可以參考下2018-05-05
springboot docker jenkins 自動(dòng)化部署并上傳鏡像的步驟詳解
這篇文章主要介紹了springboot docker jenkins 自動(dòng)化部署并上傳鏡像的相關(guān)資料,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05
源碼閱讀之storm操作zookeeper-cluster.clj
這篇文章主要介紹了源碼閱讀之storm操作zookeeper-cluster.clj的相關(guān)內(nèi)容,對(duì)其源碼進(jìn)行了簡(jiǎn)要分析,具有參考意義,需要的朋友可以了解下。2017-10-10
Linux+Docker+SpringBoot+IDEA一鍵自動(dòng)化部署的詳細(xì)步驟
這篇文章主要介紹了Linux+Docker+SpringBoot+IDEA一鍵自動(dòng)化部署的詳細(xì)步驟,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
SpringBoot導(dǎo)入mail依賴報(bào)錯(cuò)問題解決
這篇文章主要介紹了SpringBoot導(dǎo)入mail依賴報(bào)錯(cuò)問題解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Spring?Boot多個(gè)定時(shí)任務(wù)阻塞問題的解決方法
在日常的項(xiàng)目開發(fā)中,往往會(huì)涉及到一些需要做到定時(shí)執(zhí)行的代碼,下面這篇文章主要給大家介紹了關(guān)于Spring?Boot多個(gè)定時(shí)任務(wù)阻塞問題的解決方法,需要的朋友可以參考下2022-01-01

