pageContext和局部变量的区别?

4) pageContext:   保存的键值仅在本个页面有效。在未来学习Taglib过程当中,将发挥巨大作用。类变量被所有用户(浏览器)只在这一页时共享(例如例1.1),而pageContext 被某个用户(浏览器)只在这一页时才有。pageContext范围比类变量小,和局部变量是一样的,但局部变量可以在非service的方法中用,而 pageContext只能在service方法中用。 见例子2.4

5)局部变量:转化成servlet后的某个方法中的局部变量。
6)类变量:转化成servlet后的类变量。

例 2.3

<%@ page contentType="text/html; charset=GBK" %>
<html>
<body>
<% 
 request.setAttribute("rName","rmark-to-win");
 application.setAttribute("aName","amark-to-win");
 session.setAttribute("sName","smark-to-win");
 request.getRequestDispatcher("/Cookie/AddCookie").forward(request,response);
/*如用下面的response,request就取不出来了。 结果就变成如下了 null amark-to-win smark-to-win*/ 
//  response.sendRedirect("http://localhost:8080/ServletHello/Cookie/AddCookie");
%>
</body>
</html>

package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddCookie extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
      String rav=(String)request.getAttribute("rName");
      String scs=(String)this.getServletContext().getAttribute("aName");
      String sa=(String)request.getSession().getAttribute("sName");
      System.out.println(rav+" "+scs+" "+sa);
    }
}


比较pageContext,类变量和局部变量,下面给出一个例子。

例 2.4
<%@ page contentType="text/html; charset=GBK"%>
<html>
<body bgcolor="#ffffff">
    <%!double called() {
        int c=9;//局部变量可以放在service外的方法里。
/*下一句错误,因为pageContext只能放在service里面,外面can not be resolved.*/    
 //       pageContext.getAttribute("abc");
        return Math.random();
    }%>
    <%!int a = 3;%>
    <%
        int b=4;
        if (pageContext.getAttribute("abc") != null) {
            pageContext.setAttribute("abc", "xyz1");
        } else {
            pageContext.setAttribute("abc", "xyz");
        }
    %>
    <%  
        if(b==4) System.out.println(b+" is still 4");
        b++;
        System.out.println(a++);
        /*you can not write System.out.println(abc); it will report error by drawing the red line*/
        System.out.println(pageContext.getAttribute("abc"));
    %>
    <h1>JBuilder Generated JSP</h1>
</body>
</html>

更多请看:https://blog.csdn.net/qq_44594371/article/details/103167781

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值