数据交换(二)

application内置对象 
    application实现用户之间的数据共享
    void setAttribute(String key,Object value) 以keyalue的形式保存对象值
    Object getAttribute(String key) 通过key获取对象值 
    String getRealPath(String path) 返回相对路径的真实路径
  
  统计网站访问次数:
       <%
          //获取当前网站的访问次数
          Integer count=(Integer)application.getAttribute("count");
          if(count!=null){
             count++;
          }else{
             count=1;
          }
          application.setAttribute("count", count);
       %>
       <%
          out.print("当前网站访问次数:"+application.getAttribute("count"));
   
       %>

作用域
    从小到大:page(pageContext)--->request---->session---->application
    page对象作用域只在当前页面有效
    request作用域是在当前请求内有效
    session作用域是在当前会话内有效
    application对象的作用域是在应用上下文

cookie对象的常用方法:    void setMaxAge(int expiry):设置cookie的有效期,以秒为单位;    void setValue(String value):在cookie创建后,为cookie赋予新的值;    String getName():获取cookie的名称;    String getValue():获取cookie的值;    int getMaxAge():获取cookie的有效时间,以秒为单位;使用cookie:  创建cookie对象:     Cookie newCookie=new Cookie(String name,String value);  写入cookie:     response.addCookie(newCookie);  读取cookie:     <%        response.addcookie(new Cookie("username","jack"));        response.addcookie(new Cookie("password","123456"));        response.sendRedirect("info.jsp");     %>cookie有效期:    

cookie与session作用域的对象:    session作用域是在服务器端保存用户信息,cookie是在客户端保存用户信息;    session作用域中保存的值是object类型,cookie保存的值是String类型;    session作用域随会话的结束而将其存储的数据销毁,cookie可以长期保存在客户端;    cookie通常用于保存不重要的用户信息,重要的信息使用session作用域保存; 

猜你喜欢

转载自www.cnblogs.com/lowerma/p/11139429.html