JSP中session、cookie和application的使用

一、session (单用户使用)

1.用处:注册成功后自动登录,登录后记住用户状态等

使用会话对象session实现,一次会话就是一次浏览器和服务器之间的通话,会话可以在多次请求中保存和使用数据。

2.语法:

public void setAttribute(String name, Object o){}
session.setAttribute("name", "YeHuan"); // 此处的Object为String类型

public Object getAttribute(String name,){}
String str = (String)session.getAttribute("name");

3.工作方式

每个session都有一个唯一的sessionid,存储于服务器端。

String str = session.getId();

4.清除和过期

a.程序主动清除session数据

方法一:设置会话失效(所有属性都失效)

session.invalidate();

方法二:移除会话的一个属性

session.removeAttribute("name");

b.服务器主动清除长时间没有再次发出请求的session(如30分钟)

设置会话过期时间

方法一:在程序中写

session.setMaxInactiveInterval(int interval); <!-- interval的单位是秒 -->

方法二:修改web.xml文件

<session-config>
  <session-timeout>30</session-timeout> <!-- 30的单位是分钟 -->
</session-config>

 

二、cookie

1.创建cookie

<%
String username = "YeHuan";
Cookie cookie = new Cookie("name",URLEncoder.encode(username, "utf-8")); cookie.setMaxAge(60*60); <!-- 设置有效期 --> response.addCookie(cookie);
%>

2.读取cookie

<%
Cookie[] data = request.getCookies();
for(int i=0;i<data.length;i++){
    if(data[i].getName().equals("name"))
        out.print("cookie:"+URLDecoder.decode(data[i].getValue(), "utf-8"));
}
%>

 

三、application

1.创建application

application.setAttribute("count", new Integer(1));

2.读取application

Integer i = (Integer)application.getAttribute("count");

3.案例

计算页面的访问次数

<%
    Object count = application.getAttribute("count");
    if(count==null){
        application.setAttribute("count", new Integer(1));
    }else{
        Integer c = (Integer)count;
        application.setAttribute("count", c.intValue()+1);
    }
    Integer i = (Integer)application.getAttribute("count");
    out.print(i);
%>

四、request、session和application三者的比较

1.相同点

都可以存储属性

2.不同点

a.request中存储的数据仅在一个请求中可用;

b.session中存储的数据在一个会话的有效期内可用;

c.application存储的数据在整个web项目中可用。

posted @ 2019-05-16 20:00  想看云飞却没风~  阅读(615)  评论(0编辑  收藏  举报