国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java web中使用cookie記住用戶的賬號和密碼

2019-11-26 13:17:17
字體:
供稿:網(wǎng)友

畢業(yè)設(shè)計中需要用到記住賬號密碼的功能,網(wǎng)上搜到了一個解決方案,自己稍加改造就是下面的方法。

首先是登錄的頁面,當(dāng)用戶勾選記住密碼,傳遞給controller(我用的SSM框架),后臺設(shè)置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" %> <!-- 引入相關(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" %> <!-- 進入資源文件 --> <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:'請輸入用戶名'" value="<%=name %>"               style="width:240px;height:30px;">             <a id="dd" href="#" title="用戶的賬號不能為空" 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:'請輸入密碼'" 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" />記住賬號</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('登錄消息提示','用戶的賬號不能為空','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)到主頁面        // 這里先判斷是否有歷史請求,如果有就再次訪問之前的頁面        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ù)器返回異常,請稍后重試!','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;  /**   * 登錄系統(tǒng)   * @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("提交的參數(shù)為空!");   }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());     }     // 跳轉(zhuǎn)到主頁        logger.info("用戶:"+loginBean.getAccountnumber()+"成功進入系統(tǒng)");      return responseSuccess(loginBean, "登錄成功");    }   }  }  /**   * 退出系統(tǒng)登錄   * @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+",退出系統(tǒng)登錄...");   // 設(shè)置session為空   request.getSession().setAttribute("user", null);   // 頁面跳轉(zhuǎn)   return "login";  } } 

運行效果:

輸入賬號密碼登錄后:

退出后重新登錄:

以上所述是小編給大家介紹的java web中使用cookie記住用戶的賬號和密碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 潞城市| 文成县| 济阳县| 永德县| 桂阳县| 安福县| 灌云县| 交城县| 桃江县| 荣昌县| 万安县| 竹北市| 台前县| 尚义县| 磐安县| 铜梁县| 汉阴县| 得荣县| 山西省| 九江市| 林芝县| 镇平县| 阿拉善左旗| 新蔡县| 织金县| 美姑县| 长治县| 香港| 通州市| 安丘市| 乐山市| 邵阳市| 墨脱县| 岳阳市| 凤凰县| 渝北区| 涟源市| 丽水市| 金塔县| 儋州市| 石嘴山市|