jsp 中作用域的总结

1、request

 setAttribute()   //作用于仅限于一次请求
request.setAttribute("key","value");

转发:服务器内部自动完成了跳转,服务器行为无形中延长了request的作用域


2、page: this   作用域仅限于当前页面



3、session setAttribute()作用域?      一次会话;

    会话:一个会话就是服务器和客户端的一次通话;

                会话可以在多次请求中保存和使用数据

    服务器端使用的记录客户状态的机制--sessionId 每一个session有一个唯一的sessionId

    session.getId()

    session是单用户、多页面可共享的 session保存在服务器端

session的清除和过期

      session.Invalidate();

      session.removeAttribute("**");

1)设置session存在的最大值      服务器主动删除

session.setMaxInactiveInterval(5);      //单位是秒

2)  客户端手动删除

         主页面中添加超链接

<a href="<%=request.getContextPath() %>/pages/loginout.jsp">注销</a>
        跳转的页面
  <%
      //用户注销
      //session.invalidate();
      session.removeAttribute("user");
      response.sendRedirect(request.getContextPath()+"/index.jsp");
   %>

3)配置web.xml     单位:分钟

<session-config>
                        <session-timeout>30</session-timeout>
</session-config>

      cookie:跟踪用户的整个会话(不常用)

        cookie通过在客户端记录信息

            原理:给客户端发送一个通行证,每个客户一个

cookie本质是文本信息

//cookie的使用
			//如果有中文
			username = URLEncoder.encode(username,"utf-8");
			Cookie cookie = new Cookie("username",username);
			//设置路径,这个路径即该工程下都可以访问该cookie 如果不设置路径,那么只有设置该cookie路径及其子路径可以访问
			cookie.setPath("/");
			//设置cookie生命周期
			cookie.setMaxAge(60*60);
			response.addCookie(cookie);
跳转的网页
   <%
           		String username = "";
         		Cookie[] cookies = request.getCookies();
         		if(cookies!=null && cookies.length!=0){
         			for(int i=0;i<cookies.length;i++){
         				System.out.println(cookies[i].getName());
         				if(cookies[i].getName().equals("username")){
         					username = cookies[i].getValue();
         					username = URLDecoder.decode(username,"utf-8");
         				}
         			}
         		}
     %>

4、application

 可以实现计数器

<%
			    Object count=application.getAttribute("count");
			    if(count==null){
			    	//application中未存放count
			    	application.setAttribute("count", 1);
			    }else{
			    	//application中已经存放count
			    	Integer i=(Integer)count;
			    	application.setAttribute("count", i+1);
			    }
			    Integer icount=(Integer)application.getAttribute("count");
			    out.println("页面被访问了"+count+"次");
 %>

总结: request session application 三个对象对比

相同点:都可以存储属性

不同点:*request 中存储的数据仅在一次请求中使用(转发可用,重定向不能用,只能用session)

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

              *application 中存储的数据在整个Web项目中使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值