jsp内置对象作用域白话演示

内置对象就是JSP中不需要自己定义和声明的对象,可以在JSP中直接使用。
JSP中有9大内置对象,它们有两个常用的方法:
setAttribute("key","value"):存值,以键值对的形式,key是键,value是值。
getAttribute("key"):取值,通过key取曾经set到内置对象中的值。
简要介绍一下pageContext,request,session,application这四个内置对象的作用范围的试验小方法:
1.pageContext作用域:
在同一页面中正常传值,跳转后值消失。
2.request作用域:
页面发生跳转,如果是地址栏信息没有改变的情况(称为一次请求),则正常传值。
3.session作用域:
浏览器未关闭(会话状态),得到值后数据一直在,默认30分钟后销毁。浏览器关闭(一次会话结束),值消失。常用于用户信息的保存,如登录状态。
4.application作用域:
服务器关闭后,数据才消失。常用于统计网站点击量,访问量等。

在demo01中写上这些代码,在地址栏输入http://localhost:8080/JSP_002/demo01.jsp,肯定是都能得到结果的。

<%
int num=0;
pageContext.setAttribute("p",1);
request.setAttribute("r",1);
session.setAttribute("s",1);

%>
<%
System.out.println( pageContext.getAttribute("p"));
System.out.println( request.getAttribute("r"));
System.out.println( session.getAttribute("s"));

%>
前三个一起验证:
如果在demo01.jsp中加入跳转到demo2.jsp,即下面这行代码:

<jsp:forward page="demo2.jsp"></jsp:forward>
如果把上面这行代码加入到最后面,浏览器打开demo01.jsp,那么控制台得到结果:1 1 1 null 1 1 (demo01.jsp执行编译完,set和get都在同一个页面所以值全部得到,然后跳转到demo2.jsp,pageContext的值消失)
如果放到两段Java代码的中间,浏览器打开demo01.jsp,那么得到结果:null 1 1 (demo01.jsp执行完前一段代码,还没有执行到后一段get方法时就跳转到了demo2.jsp,由demo2.jsp的get方法获得的值,pageContext的值消失,request能得到值是因为虽然执行跳转到demo2.jsp的代码但未使地址栏发生改变,还是demo01.jsp)

以下我们试验把跳转代码放入两段Java代码中间,主要测试跳转到demo2.jsp后的执行结果。
session是指浏览器未关闭,第一次请求得到的信息会保留。
操作1:直接打开demo2.jsp,执行结果为:null null null (set方法在demo01.jsp里面,当直接打开demo2.jsp页面,地址栏已经不是demo01.jsp了,所以由于作用域的不同,只有application的值是存在的)
操作2:先打开demo01.jsp,再打开demo2.jsp,执行结果:先得到null 1 1 (同标红部分),null null 1 (第一个null,set和get不在同一个页面,所以值未得到,第二个null地址栏地址栏直接改变了,打开的是demo2.jsp,而不再是set所在的demo1.jsp,所以值未得到。第三个1是因为打开demo01.jsp后,未关闭浏览器,直接打开demo2.jsp,执行demo01的时候,session是可以得到值了的,浏览器未关闭,值就会保留,所以再直接打开demo2.jsp后,值是存在的)


最后验证一下application:
<%
if(application.getAttribute("n")==null){ //num相当于key,num的值一直保留,如果其它jsp文件里也用的num这个名,那么其它页面的访问量就都算在一起了,如果用其它名则各自算各自的
application.setAttribute("n",0);
}
Integer nu=(Integer)application.getAttribute("n");
application.setAttribute("n",nu+1);
nu=(Integer)application.getAttribute("n");
System.out.println(nu);
%>
或者类型转换一下
<% if(application.getAttribute("num")==null){ //num相当于key,num的值一直保留,如果其它jsp文件里也用的num这个名,那么其它页面的访问量就都算在一起了,如果用其它名则各自算各自的
application.setAttribute("num",new Integer(0));
}
Integer count=(Integer)application.getAttribute("num");
application.setAttribute("num",new Integer(count.intValue()+1));
count=(Integer)application.getAttribute("num");
System.out.println(count.intValue());
%>
<center>这是第<%=count.intValue()%>个访问者!</center>
执行结果:只要没有重启Tomcat服务器,每次刷新或者重启浏览器,数据都会保留,上面代码是一个简易的访问量例子,每点开一次,访问值加1。

原文地址:https://www.cnblogs.com/tendo/p/7009862.html