web应用四种属性范围

来源:互联网 发布:中国游戏中心 mac 编辑:程序博客网 时间:2024/06/05 18:46

在Web应用程序中,页面的数据通过不同范围的参数进行传递,在传递的过程中,按照不同的数据生命周期,我们定义了 page/request/session/application4种数据存储范围。

以上4中变量都是jsp的内置变量,都是小写开头。

1、pageContext

只在当前服务器页面中进行数据的存储和读取,页面级别的

<%

         pageContext.setAttribute("num",2);

//

//

         Integernum = (Integer) pageContext.getAttribute("num");

         out.print(num);

%>


2、request

在服务器内部进行页面跳转的时候,可以进行request.setAttribute()进行属性设值。

服务器内部跳转:地址栏是不会发生变化的,只在服务器内部进行jsp/servlet的请求,我们一般用做多层结构中。

request范围内的变量只在单次的服务器端页面跳转内有效。

<%

         request.setCharacterEncoding("UTF-8");

         Stringusername = request.getParameter("username");

         Stringpassword = request.getParameter("password");

         Studentstu = StudentService.getStudentByUsernameAndPwd(username, password);

         if(null != stu) {

                  request.setAttribute("students",StudentService.getAllStudents());

                  request.setAttribute("stu",stu);             

%>

<jsp:forward page="success.jsp"/>

<%

         }else {

%>

<jsp:forward page="index.jsp">

         <jsp:paramname="msg" value="账号或密码错误" />

</jsp:forward>

<%

         }

%>
在success.jsp中获取request设置的属性值

<%

                  Studentstu1 = (Student)request.getAttribute("stu");

                  List<Student>students = (List<Student>) request.getAttribute("students");

       %>


3、session

会话级别的变量,我们一般使用Session处理用户的登录信息

简单的理解,打开一个浏览器,无论你打开多少的便签页,session的会话级变量都会存在,除非使用session.removeAttribute()将其显示的销毁。


4、application

服务器级别的变量,只要服务启动未关闭,该变量就会一直存在,除非显示的销毁。

<%

         Integernum = (Integer) application.getAttribute("num");

         if(null == num) {

                  application.setAttribute("num",1);

         }else {

                  application.setAttribute("num",num+1);

         }

%>

该页面被访问<%=application.getAttribute("num")%>次
原创粉丝点击