EasyMall第九天

来源:互联网 发布:跑腿软件哪个好 编辑:程序博客网 时间:2024/05/22 16:12

8.17(周期、范围、功能)

  • Cookie:客户端技术,程序把每个用户的数据写到客户端
    小案例:
    1.生成本次访问的时间字符串
    2.先展示上一次访问的时间,再生成新的时间字符串进行存储
    3.使用Cookie:response.setHeader(“Set-Cookie”,data);
    request.getHeader(“Cookie”);
    4.注:第一次访问时注意判null
    API的使用:
    String time = new Date().toLocaleString();
    response.setContent(“text/html;charset=utf-8”);
    //使用Cookie类
    Cookie cookie=new Cookie(String name,String value);//value值不能为空格,解决办法:URLEncoder
    response.addCookie(cookie);
    response.getWrite().write();
    获取cookie数组(只能是数组,然后遍历进行筛选)

    注:如果默认添加一个cookie到session到response中,不附加任何信息
    如果不设置maxAge(/秒),则默认为0,持续时间为浏览器开启到结束

    setPath();如果没有设置,则null传给浏览器,path默认添加为父目录(项目名++)。最好手动设置一下(request.getContextPath+”“)
    getPath();

    域名设置:doMomain();永远不要设定;因为市面上的

    调用程序删除Cookie:判断Cookie的name和path和doMomain是否一致,一致的话进行设置setAge(0)并response.addCookie(cookie);
    删除Cookie原理:将maxAge不为0的Cookie置为0

    记住帐号原理:servlet中(判断是否选中‘记住帐号’【记住: new一个cookie并设置其name=username和value=request.getParameter(“username”)、path=request.getContextPath()、saxAge=3600】【不记住(删除cookie):设置name=username、value=”“、path=request.getContextPath()、saxage=0】);

            jsp中(获取cookie:【cookie==null username="" checked不设置】【cookie!=null username=URLDecoder.decode(cookie.getValue(),"utf-8") 并且将chenked设置为checked】);        注:cookie保存之前或获取之前需编码和解码。
  • Session:服务端技术,在服务端开辟一段空间进行存储用户数据,通过Cookie存储id进行身份设置。
    1.域对象
    2.方法:set/get/remove + Attribute() getAttributeName()
    3.生命周期:超时(一般30分钟后)、自杀(session.invalidate())、意外身亡(服务器非正常关闭)
    案例:购物车【物品1->session;物品2->session;物品3->session;…;最后进行全部进行提交】
    HttpSession session = request.getSession(true可填可不填);//有:用 没有:进行创建
    HttpSession session = request.getSession(false);//有:用 没有:返回null
    session不需要addsession,servlet将自动进行提交。

    【Buy中:jsp中禁用session session=“false”(jsp本质是servlet,访问页面是);服务器中 HttpSession session = request.getSession(true可填可不填)】
    【Pay中:HttpSession session = request.getSession(false); 不为null-购物车有东西;为null,购物车没东西;注:支付完将session中数据进行更新!】

  • 解决乱码
    String prod=null;
    if(“GET”.equals(request.getMethod())){
    prod=new String(request.getParameter(“prod”).getBytes(“ios-8859-1”),”utf-8”);
    } else if(“POST”.equals(request.getMethod())){
    request.setCharacterEncoding(“utf-8”);
    prod=request.getParameter(“prod”);
    }