java内置对象生命周期

JSP 内置对象作⽤域

    4个
    page、request、session、application
   公共方法:setAttribute、getAttribute
 
page 作⽤域:对应的内置对象是 pageContext。
request 作⽤域:对应的内置对象是 request。
session 作⽤域:对应的内置对象是 session。
application 作⽤域:对应的内置对象是 application。
page < request < session < application
 
page 只在当前⻚⾯有效。
request 在⼀次请求内有效。
session 在⼀次会话内有效。
application 对应整个 WEB

 

page

 

 

 request

 

session

会话内可以有无数个请求

 

 

 application

只有tomcat关了才失效

 

一个例子,网站浏览量记录

1.永远显示1

<%
    int count=0;
    count++;
%>
您是当前的第<%=count%>位访客

2.永远显示1

<%
    Integer count=(Integer) request.getAttribute("count");
    if(count== null){
        count=1;
        request.setAttribute("count",count);
    }else {
        count++;
        request.setAttribute("count",count);
    }
%>
您是当前的第<%=count%>位访客

原因:刷新后request没了,永远都是count=null,变成1

3.能正确显示的

<%
    Integer count=(Integer) session.getAttribute("count");
    if(count== null){
        count=1;
        session.setAttribute("count",count);
    }else {
        count++;
        session.setAttribute("count",count);
    }
%>
您是当前的第<%=count%>位访客

 

 但在不同浏览器中数据不同

 

所以用application

<%
    Integer count=(Integer) application.getAttribute("count");
    if(count== null){
        count=1;
        application.setAttribute("count",count);
    }else {
        count++;
        application.setAttribute("count",count);
    }
%>
您是当前的第<%=count%>位访客

 

posted @ 2021-01-23 10:48  Hanabi_521  阅读(124)  评论(0编辑  收藏  举报