java - 利用cookie实现记住用户名方便之后登陆

来源:互联网 发布:淘宝手机膜评价 编辑:程序博客网 时间:2024/06/05 06:09

前情:
cookie中不能有中文,所以如果要保存中文时则用
URLEncoder.encode先编码,取cookie值时再用URLDecoder.decode解码
第一步:

//获得cookie//【ServletActionContext.getRequest()】这是struts2中的写法,servlet直接request即可    public String getCookie(){        Cookie cookies[] = ServletActionContext.getRequest().getCookies();        for(int i=0;cookies!=null && i<cookies.length;i++){            Cookie cookie = cookies[i];            if(cookie.getName().equals("username")){                return URLDecoder.decode(cookie.getValue());            }        }        return "";    }

2.在登陆成功后【用户名和密码正确】加上一下代码:

//如果用户的用户名cookie为空,则发送cookie                if(getCookie()==""||!getCookie().equals(user.getUsername())){                    Cookie cookie = new Cookie("username",URLEncoder.encode(user.getUsername()));                    //设置时间为1年                    cookie.setMaxAge(365*24*3600);                       cookie.setPath("/");                    //把cookie给浏览器                    ServletActionContext.getResponse().addCookie(cookie);                }

记住密码也是同样的道理,是不是很简单~

jsp页面:

<script type="text/javascript">            $(function(){            $.ajax({                    type:"get",                 url:"${pageContext.request.contextPath}/user_loginUI.do?",                    async:false,                    dataType:"json",                    cache:false,                    success:function(data){                        //给用户名输入框的val赋值                                     $("#text").val(data.user.username);                                                                //alert(data.user.username);                    }            });    });</script>
0 0
原创粉丝点击