在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java web中使用cookie记住用户的账号和密码

2017-3-7 12:51| 发布者: zhangjf| 查看: 1176| 评论: 0

摘要: 毕业设计中需要用到记住账号密码的功能,网上搜到了一个解决方案,自己稍加改造就是下面的方法。 首先是登录的页面,当用户勾选记住密码,传递给controller(我用的SSM框架),后台设置cookie的值,然后下次登录的时候 ...

毕业设计中需要用到记住账号密码的功能,网上搜到了一个解决方案,自己稍加改造就是下面的方法。

首先是登录的页面,当用户勾选记住密码,传递给controller(我用的SSM框架),后台设置cookie的值,然后下次登录的时候就不用再次输入账号和密码了。

login.jsp的代码:

  1. <%@page import="org.apache.commons.lang.StringUtils"%>
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"
  3. pageEncoding="UTF-8"%>
  4. <%@include file="public/nocache.jsp" %>
  5. <%@include file="public/header.jsp" %>
  6. <!-- 引入相关的js -->
  7. <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
  8. <style>
  9. body{
  10. margin:0px;
  11. padding:0px;
  12. }
  13. .wrapper{
  14. width:100%;height:100%;position:fixed;
  15. }
  16. .content{
  17. width:100%;
  18. height:100%;
  19. position:relative;
  20. text-align:center;
  21. }
  22. .login{
  23. width:1050px;
  24. height:450px;
  25. position:absolute;
  26. top:50%;
  27. left:50%;
  28. margin-top:-225px;
  29. margin-left:-525px;
  30. }
  31. </style>
  32. <script type="text/javascript">
  33. window.history.forward();
  34. window.onbeforeunload=function (){
  35. }
  36. </script>
  37. <%@include file="public/headertop.jsp" %>
  38. <!-- 进入资源文件 -->
  39. <body>
  40. <%-- 读取cookie --%>
  41. <%
  42. String name = "";
  43. String password = "";
  44. try{
  45. Cookie[] cookies = request.getCookies();
  46. if(cookies!=null){
  47. for(int i = 0;i<cookies.length;i++){
  48. if(cookies[i].getName().equals("cookie_user")){
  49. String values = cookies[i].getValue();
  50. // 如果value字段不为空
  51. if(StringUtils.isNotBlank(values)){
  52. String[] elements = values.split("-");
  53. // 获取账户名或者密码
  54. if(StringUtils.isNotBlank(elements[0])){
  55. name = elements[0];
  56. }
  57. if(StringUtils.isNotBlank(elements[1])){
  58. password = elements[1];
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }catch(Exception e){
  65. }
  66. %>
  67. <div class="wrapper" style="">
  68. <div class="content">
  69. <div class="login">
  70. <!-- 主要的内容部分开始 -->
  71. <div class="easyui-layout" fit="true" border="false">
  72. <div region="west" style="width:550px;text-align:center;" border="false">
  73. <div class="easyui-layout" fit="true" border="false">
  74. <div region="west" border="false" style="width:250px;height:390px;background:url(${pageContext.request.contextPath}/img/banner-jkrzbg.png)">
  75. </div>
  76. <div region="center" style="font-family:'微软雅黑';" border="false">
  77. <p style="position: relative;margin-top:200px;padding-left:20px;">
  78. <span style="font-size:30px;font-weight:800;">汽车维修管理系统</span><br/>
  79. <span>Vehicle Maintenance Management System</span>
  80. </p>
  81. </div>
  82. </div>
  83. </div>
  84. <div region="center" border="false" style="width:520px;height:480px;">
  85. <div class="easyui-layout" fit="true" border="false">
  86. <div region="north" style="height:80px;" border="false">
  87. </div>
  88. <div region="west" style="width:90px;position: relative;" border="false">
  89. <img src="${pageContext.request.contextPath}/img/split.png" style="position:absolute;left:0px;top:30px;"/>
  90. </div>
  91. <div region="center" border="false">
  92. <div class="easyui-panel" title="用户登录" iconCls="icon-user"
  93. style="text-align: center;width:300px;height:260px;padding-top:50px;">
  94. <form id="ff" method="post">
  95. <div>
  96. <input id="account" class="easyui-textbox" name="accountnumber"
  97. data-options="iconCls:'icon-man',prompt:'请输入用户名'" value="<%=name %>"
  98. style="width:240px;height:30px;">
  99. <a id="dd" href="#" title="用户的账号不能为空" class="easyui-tooltip"></a>
  100. </div>
  101. <div style="margin-top: 20px;">
  102. <input id="passwords" class="easyui-textbox" name="passwords" type="password"
  103. data-options="iconCls:'icon-lock',prompt:'请输入密码'" value="<%=password %>"
  104. style="width:240px;height:30px;">
  105. </div>
  106. <div style="margin-top: 10px;" style="text-align:left;" >
  107. <span style="float:left;padding-left:30px;font-size:12px;"><input id="flag" name="flag" type="checkbox" value="1" checked="checked" />记住账号</span>
  108. </div>
  109. <div style="clear:both;"></div>
  110. <div style="margin-top: 20px;">
  111. <p>
  112. <a href="#" id="submitbtn" style="width:80px;height:30px;" class="easyui-linkbutton" iconCls="icon-accept">登录</a>
  113. <a style="margin-left:30px;width:80px;height:30px;" href="#" class="easyui-linkbutton" iconCls="icon-arrow_undo">取消</a>
  114. </p>
  115. </div>
  116. </form>
  117. </div>
  118. </div>
  119. <div region="east" style="width:90px;" border="false">
  120. </div>
  121. <div region="south" style="height:0px;" border="false">
  122. </div>
  123. </div>
  124. </div>
  125. </div>
  126. <!-- 主要的内容部分结束 -->
  127. </div>
  128. </div>
  129. </div>
  130. <script type="text/javascript">
  131. $(function(){
  132. console.log("[汽车维修管理系统n codeby:pengchann email:dntchenpeng@163.com n csdn:http://blog.csdn.net/w3chhhhhh/]");
  133. // 提交表单
  134. $("#submitbtn").click(function(){
  135. // 判断是否为空
  136. if($("#account").val()==""){
  137. $.messager.alert('登录消息提示','用户的账号不能为空','info');
  138. return;
  139. }
  140. if($("#passwords").val()==""){
  141. $.messager.alert('登录消息提示','用户的密码不能为空','info');
  142. return;
  143. }
  144. $("#ff").submit();
  145. });
  146. $('#ff').form({
  147. url:"${pageContext.request.contextPath}/users/login.html",
  148. success:function(data){
  149. data = JSON.parse(data);
  150. try{
  151. if(data.isError){
  152. $.messager.alert('登录消息提示',data.errorMsg,'info');
  153. }else{
  154. //$.messager.alert("登录消息提示","登录成功!",'info');
  155. // 如果成功,就跳转到主页面
  156. // 这里先判断是否有历史请求,如果有就再次访问之前的页面
  157. var hisurl = '${hisURL}';
  158. if(hisurl!=null&&hisurl.length>0){
  159. window.location.href="${pageContext.request.contextPath}"+hisurl;
  160. }else{
  161. window.location.href="${pageContext.request.contextPath}/index/main.html";
  162. }
  163. }
  164. }catch(e){
  165. $.messager.alert("登录消息提示",'服务器返回异常,请稍后重试!','info');
  166. }
  167. },
  168. error:function(error){
  169. $("#ff").form("clear");
  170. }
  171. });
  172. });
  173. </script>
  174. </body>
  175. </html>
复制代码

后台处理的java部分代码:

  1. package com.javaweb.controller;
  2. import javax.servlet.http.Cookie;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import org.apache.commons.lang.StringUtils;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.context.annotation.Scope;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.ui.Model;
  12. import org.springframework.web.bind.annotation.PathVariable;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.ResponseBody;
  15. import com.alibaba.fastjson.JSON;
  16. import com.javaweb.entity.Account;
  17. import com.javaweb.service.impl.ServiceFactory;
  18. import com.javaweb.utils.BaseController;
  19. import com.javaweb.views.LoginBean;
  20. /**
  21. * 用户信息控制器
  22. * @author cp
  23. *
  24. */
  25. @Controller
  26. @Scope("prototype")
  27. @RequestMapping("/users")
  28. public class UserInfoController extends BaseController{
  29. private static final Logger logger = LoggerFactory.getLogger(UserInfoController.class);
  30. @Autowired
  31. private ServiceFactory serviceFactory;
  32. /**
  33. * 登录系统
  34. * @param request 请求
  35. * @param model model
  36. * @param account 账户信息
  37. * @return
  38. */
  39. @RequestMapping("/login")
  40. @ResponseBody
  41. public String login(HttpServletRequest request,HttpServletResponse response,Model model,Account account){
  42. logger.info("用户尝试登录:"+JSON.toJSONString(account));
  43. if(account==null){
  44. return responseFail("提交的参数为空!");
  45. }else{
  46. if(StringUtils.isBlank(account.getAccountnumber())){
  47. return responseFail("用户的账号为空");
  48. }
  49. if(StringUtils.isBlank(account.getPasswords())){
  50. return responseFail("用户的密码为空");
  51. }
  52. LoginBean loginBean = null;
  53. loginBean = serviceFactory.getUserValidateService().userislawable(account);
  54. if(loginBean==null){
  55. return responseFail("用户名或者密码输入不正确");
  56. }else{// 如果成功
  57. // 把loginbean放到session中
  58. request.getSession().setAttribute("user", loginBean);
  59. // 放到cookie中
  60. String flag = request.getParameter("flag");
  61. // 如果需要记住账户就存储账号和密码
  62. if(flag!=null&&flag.equals("1")){
  63. Cookie cookie = new Cookie("cookie_user",loginBean.getAccountnumber()+"-"+loginBean.getPasswords());
  64. cookie.setMaxAge(60*60*24*3);// 保存
  65. response.addCookie(cookie);
  66. logger.info("存储用户的cookie:"+loginBean.getAccountnumber()+"-"+loginBean.getPasswords());
  67. }else{// 如果没有要求记住账户密码,就保存账户
  68. Cookie cookie = new Cookie("cookie_user", loginBean.getAccountnumber());
  69. cookie.setMaxAge(60*60*24*30);
  70. response.addCookie(cookie);
  71. logger.info("存储用户的cookie:"+loginBean.getAccountnumber());
  72. }
  73. // 跳转到主页
  74. logger.info("用户:"+loginBean.getAccountnumber()+"成功进入系统");
  75. return responseSuccess(loginBean, "登录成功");
  76. }
  77. }
  78. }
  79. /**
  80. * 退出系统登录
  81. * @param request 请求
  82. * @param model 模型
  83. * @param accountnum 账户号
  84. * @return
  85. */
  86. @RequestMapping("/{accountnum}/logout.html")
  87. public String logout(HttpServletRequest request,Model model,@PathVariable("accountnum") String accountnum){
  88. logger.info("用户"+accountnum+",退出系统登录...");
  89. // 设置session为空
  90. request.getSession().setAttribute("user", null);
  91. // 页面跳转
  92. return "login";
  93. }
  94. }
复制代码

运行效果:

输入账号密码登录后:

退出后重新登录:

以上所述是小编给大家介绍的java web中使用cookie记住用户的账号和密码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对程序员之家网站的支持!

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-4 02:07

Copyright 2015-2025 djqfx

返回顶部