畢業設計中需要用到記住賬號密碼的功能,網上搜到了一個解決方案,自己稍加改造就是下面的方法。
首先是登錄的頁面,當用戶勾選記住密碼,傳遞給controller(我用的SSM框架),後台設置cookie的值,然後下次登錄的時候就不用再次輸入賬號和密碼了。
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" %> <!-- 引入相關的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" %> <!-- 進入資源文件--> <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 style=""> <div> <div> <!-- 主要的內容部分開始--> <div fit="true"> <div region="west"> <div fit="true"> <div region="west"> </div> <div region="center" style="font-family:'微軟雅黑';"> <p style="position: relative;margin-top:200px;padding-left:20px;"> <span style="font-size:30px;font-weight:800;">汽車維修管理系統</span><br/> <span>Vehicle Maintenance Management System</span> </p> </div> </div> </div> <div region="center"> <div fit="true"> <div region="north" style="height:80px;"> </div> <div region="west"> <img src="${pageContext.request.contextPath}/img/split.png" style="position:absolute;left:0px;top:30px;"/> </div> <div region="center"> <div iconCls="icon-user" style="text-align: center;width:300px;height:260px;padding-top:50px;"> <form id="ff" method="post"> <div> <input id="account" name="accountnumber" data-options="iconCls:'icon-man',prompt:'請輸入用戶名'" value="<%=name %>" > <a id="dd" href="#"></a> </div> <div style="margin-top: 20px;"> <input id="passwords" name="passwords" type="password" data-options="iconCls:'icon-lock',prompt:'請輸入密碼'" value="<%=password %>" > </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" />記住賬號</span> </div> <div style="clear:both;"></div> <div style="margin-top: 20px;"> <p> <a href="#" id="submitbtn" iconCls="icon-accept">登錄</a> <a style="margin-left:30px;width:80px;height:30px;" href="#" iconCls="icon-arrow_undo">取消</a> </p> </div> </form> </div> </div> <div region="east"> </div> <div region="south" style="height:0px;"> </div> </div> </div> </div> <!-- 主要的內容部分結束--> </div> </div> </div> <script type="text/javascript"> $(function(){ console.log("[汽車維修管理系統/n codeby:pengchan/n email:[email protected] /n csdn:http://blog.csdn.net/w3chhhhhh/]"); // 提交表單$("#submitbtn").click(function(){ // 判斷是否為空if($("#account").val()==""){ $.messager.alert('登錄消息提示','用戶的賬號不能為空','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'); // 如果成功,就跳轉到主頁面// 這裡先判斷是否有歷史請求,如果有就再次訪問之前的頁面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("登錄消息提示",'服務器返回異常,請稍後重試!','info'); } }, error:function(error){ $("#ff").form("clear"); } }); }); </script> </body> </html>後台處理的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; /** * 登錄系統* @param request 請求* @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("提交的參數為空!"); }else{ if(StringUtils.isBlank(account.getAccountnumber())){ return responseFail("用戶的賬號為空"); } 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"); // 如果需要記住賬戶就存儲賬號和密碼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("存儲用戶的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("存儲用戶的cookie:"+loginBean.getAccountnumber()); } // 跳轉到主頁logger.info("用戶:"+loginBean.getAccountnumber()+"成功進入系統"); return responseSuccess(loginBean, "登錄成功"); } } } /** * 退出系統登錄* @param request 請求* @param model 模型* @param accountnum 賬戶號* @return */ @RequestMapping("/{accountnum}/logout.html") public String logout(HttpServletRequest request,Model model,@PathVariable("accountnum") String accountnum){ logger.info("用戶"+accountnum+",退出系統登錄..."); // 設置session為空request.getSession().setAttribute("user", null); // 頁面跳轉return "login"; } }運行效果:
輸入賬號密碼登錄後:
退出後重新登錄:
以上所述是小編給大家介紹的java web中使用cookie記住用戶的賬號和密碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!