.11四种属性范围

来源:互联网 发布:skype聊天软件下载 编辑:程序博客网 时间:2024/05/19 09:48

.1.1       request

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

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

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

<%

         request.setCharacterEncoding("UTF-8");

 

         String username = request.getParameter("username");

         String password = request.getParameter("password");

 

         Student stu = 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:param name="msg" value="账号或密码错误" />

</jsp:forward>

<%

         }

%>

 

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

<%

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

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

         %>

.1.2       关于分层设计的概念

在MVC设计模式中的业务处理步骤

(1)   从客户端获取页面参数到指定的服务器端页面(jsp),使用request.getParameter();

(2)   使用参数在Service方法中进行业务逻辑的处理,并返回处理结果(一般为JavaBean);

(3)   将处理结果放到页面级的变量request中,request.setAttribute(“name”,Object);

(4)   通过服务器端的页面跳转(jsp:forward)到相应的视图层(success.jsp)进行数据的获取和页面展现输出,request.getAttribute(“name”)

.1.3       pageContext

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

<%

         pageContext.setAttribute("num", 2);

//

//

 

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

         out.print(num);

%>

.1.4       session

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

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

.1.5       application

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

<%

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

         if (null == num) {

                   application.setAttribute("num", 1);

         } else {

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

         }

%>

该页面被访问<%=application.getAttribute("num") %>

原创粉丝点击