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; }

 

posted @ 2018-07-24 16:23  NYfor2018  阅读(4140)  评论(2编辑  收藏  举报