JSP基本语法(四)

1.JSP内置对象

 

2. 4种属性范围

属性范围: 表示一个内置的对象可以在多少个页面中进行保存并继续使用

属性的操作方法

2.1.page:(使用pageContext表示)表示把一个属性设置在本页中,跳转后无法取到。

<body>
<%
  //设置page属性范围,只能在本JSP页面中获取到
  pageContext.setAttribute("name", "mxzer");
  pageContext.setAttribute("birthday", new Date());
%>
<%
  //获取page属性,并向下转型
  String name = (String)pageContext.getAttribute("name");
  Date bir = (Date)pageContext.getAttribute("birthday");
%>
   <!--输出信息-->
  <h2>姓名:<%=name%></h2>
  <h2>生日:<%=bir%></h2>
</body>

特殊设置

<%
//设置page属性
pageContext.setAttribute("name", "mxzer",pageContext.REQUEST_SCOPE);
pageContext.setAttribute("birthday", new Date(),pageContext.REQUEST_SCOPE);
%>

 

 

2.2request:客户端的请求

// 1.jsp
<%
  //设置request属性范围,在服务器端跳转获有效
  request.setAttribute("name", "mxzer");
  request.setAttribute("birthday", new Date());
%>
<jsp:forward page="2.jsp"/>

//2.jsp <%   //获取request属性,并向下转型   String name = (String)request.getAttribute("name");   Date bir = (Date)request.getAttribute("birthday"); %> <h2>姓名:<%=name%></h2> ----> mxzer <h2>生日:<%=bir%></h2> ------>.... //再次设置值 <%   //设置request属性范围,在服务器端跳转获有效   request.setAttribute("name", "mxzer002");   request.setAttribute("birthday", new Date()); %> <!--通过超链接跳转,地址栏改变了,属于客户端跳转 --> <a href="3.jsp">超链接跳转</a>

//3.jsp <%   //获取request属性,并向下转型   String name2 = (String)request.getAttribute("name");   Date bir2 = (Date)request.getAttribute("birthday"); %> <h2>姓名:<%=name%></h2> --->null <h2>生日:<%=bir%></h2>--->null

 

 2.3session属性范围:一个属性设置后,可以在任何一个与设置页面相关的页面中获取到值(服务器端跳转、客户端跳转都可以)

<%
  //设置session属性范围,在一个浏览器中有效
  session.setAttribute("name", "mxzer002");
  session.setAttribute("birthday", new Date());
%>

 

<a href="3.jsp">超链接跳转</a>,可以获取到session属性值;

再打开一个浏览器就获取不到上面的值:因为每一个新的浏览器连接上服务器后就是一个新的session。

 

2.4application:所有用户都可获取设置的属性值

application属性设置过多时,会影响服务器的性能。

<%
  //设置application属性范围,该属性保存在服务器上。
  application.setAttribute("name", "mxzer002");
  application.setAttribute("birthday", new Date());
%>

 

<a href="3.jsp">超链接跳转</a>,可以获取到application属性值;

 

posted @ 2017-02-21 18:12  Mxzer.Zhang  阅读(189)  评论(0编辑  收藏  举报