在JSP中提供了四种属性的保存范围,所谓的属性的保存范围,指的是一个设置的对象,能够在多少个页面中保存,并能够使用。java
四种属性范围:浏览器
①pageContext:只在一个页面中保存属性,跳转后无效;服务器
②request:只在一次请求中保存属性,服务器跳转后依然有效;session
③session:在一次会话范围中,不管如何跳转都有效,但新开浏览器则无效;app
④application:在整个服务器上保存,全部用户均可以使用。jsp
属性操做方法spa
NO | 方法 |
类型 |
描述 |
1 |
public void setAttribute(String name,Object value) |
普通 | 设置属性的名称和内容 |
2 | public Object getAttribute(String name) |
普通 | 根据属性名称取得内容 |
3 | public removeAttribute(String name) | 普通 | 删除指定的属性 |
四个内置对象都存在以上三个方法。code
设置属性的时候,属性的名称是String,内容是Object。Object能够设置任意内容对象
一,page范围(pageContext范围)---->表示将一个属性设置在页面上,跳转后没法取得rem
<body> <% //设置page属性范围,此范围只能在本页面起做用 pageContext.setAttribute("name","IronMan") ; pageContext.setAttribute("birthday",new Date()) ; %> <% //从page属性中取得内容,并执行向下转型,由于取得后返回的类型是Object,因此必须向下转型操做 String username = (String) pageContext.getAttribute("name") ; //向下转型,把父类对象当作子类对象,子类有而父类不必定有 Date userbirthday = (Date) pageContext.getAttribute("birthday") ; %> <h2>姓名:<%=username %></h2> <h2>年龄:<%=userbirthday %></h2> </body>
经过<jsp:forward>跳转,则跳转以后属性没法取得
<body> <% //设置page范围,此属性只能在JSP页面中起做用 pageContext.setAttribute("name","IronMan") ; pageContext.setAttribute("birthday",new Date()) ; %> <jsp:forward page="page_scope_03"></jsp:forward> <%--服务器端跳转--%> </body>
<body> <% //从page范围中取得属性,由于返回的类型是Object,因此要执行向下转型 String username = (String)pageContext.getAttribute("name") ; Date userbirthday = (Date)pageContext.getAttribute("birtyday") ; %> <h2><%=username %></h2> <h2><%=userbirthday %></h2> </body>
如今发现服务器跳转以后,发现内容取得,则一个page范围中的内容只能在一个页面内保存。
若是但愿服务器跳转以后能够继续取得属性,则使用更大范围的跳转---->request跳转
二,request属性范围
若是要在服务器跳转以后,属性还能够保存下来,则使用request属性范围操做。request属性范围表示,在服务器跳转以后,全部设置的内容依然能够保存下来。
request_scope_01.jsp
<body> <% request.setAttribute("name","IronMan") ; request.setAttribute("birthday",new Date()) ; %> <jsp:forward page="request_scope_02.jsp"></jsp:forward> </body>
request_scope_02.jsp
<body> <% String username = (String) request.getAttribute("name") ; Date userbirthday = (Date) request.getAttribute("birthday") ; %> <h2>姓名:<%=username %></h2> <h2>生日:<%=userbirthday %></h2> </body>
若是跳转换成超连接跳转,则没法取得属性,由于超连接跳转后,地址栏信息改变,属于客户端跳转而不是服务器跳转。是没法取得属性的。
<body> <% // 设置request的属性范围,此属性只能在服务器跳转中有做用 request.setAttribute("name","SuperMan") ; request.setAttribute("birthday",new Date()) ; %> <!-- 使用超连接跳转,地址栏改变,属于客户端跳转,而不是服务器跳转,因此不能取得属性 --> <a href = "request_scope_02.jsp">经过超连接取得属性</a> </body>