SpringMVC之使用cookie實現記住密碼的功能


注意:因為實現記住密碼的功能需要用到json,所以需要加上這條語句:

<script type="text/javascript" src="scripts/jquery.min.js"></script>

 一、編寫表單

<form action="login" method="post">
        <table>
            <tr>
                <td>用戶名:</td>
<td><input type="text" name="userName" id="userName" onkeyup="rememberCheck(this.value)"/></td>
            <!--onkeyup是每次對文本框的操作如輸入一個字符,都會進行rememberCheck()函數的調用-->
</tr> <tr> <td>密 碼:</td> <td><input type="password" name="password" id="password"/></td> </tr> <tr> <td>記住密碼<input type="checkbox" name="check"></td> </tr> <tr> <td><input type="submit"></td> </tr> </table> </form> </body>

 

二、編寫js函數

<script type="text/javascript">
<!--這個函數就是在userName的文本框中每輸入一個字符就會調用getCookie.action來查找是否有cookie記錄下數據-->
<!--success中的功能就是把返回到的data自動輸出到文本框中--> function rememberCheck(string){ $.ajax({ type:"POST", url: "getCookie.action", dataType:"json", data:{ userName:string, }, success:function(data){ $("#userName").val(data.userName); $("#password").val(data.password); }, error:function() { $("#password").val(""); } }); }; </script>

 

三、SpringMVC中的Controller

@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(UserInfo u,Model model,HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException{
  ...
    if(u.getUserName().equals(user.getUserName())&&u.getPassword().equals(user.getPassword())) {
      model.addAttribute("user",user);
      if(request.getParameter("check")!=null)
        addCookie(u.getUserName(), u.getPassword(), response, request);
      return "index";
    }
   ...
}

 

四、添加cookie的方法(可直接寫在SpringMVC的Controller中)

/**
     * 添加Cookie
     * @param userName
     * @param password
     * @param response
     * @param request
     * @throws UnsupportedEncodingException
     */
    public static void addCookie(String userName,String password,HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException{
        //創建cookie
        Cookie nameCookie = new Cookie(userName, password);
        nameCookie.setPath(request.getContextPath()+"/");//設置cookie路徑
        //設置cookie保存的時間 單位:秒
        nameCookie.setMaxAge(7*24*60*60);
        //將cookie添加到響應
        response.addCookie(nameCookie);            
    }

 

五、獲取cookie的Controller

    /**
     * 獲取到Cookie
   * 先把所有的Cookie獲取到,然后遍歷cookie,如果有符合項就取出來,用map裝起來發到頁面中 *
@param userName * @param request * @return */ @ResponseBody @RequestMapping(value="/getCookie",method=RequestMethod.POST) public Map<String, String> initCookie(String userName, HttpServletRequest request){ Cookie[] cookie = request.getCookies(); Map<String, String> map = new HashMap<>(); for(Cookie c : cookie) { if(c.getName().equals(userName)) { String password = c.getValue(); map.put("userName", userName); map.put("password", password); return map; } } return null; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM