前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >pageContext和局部变量的区别?

pageContext和局部变量的区别?

作者头像
马克java社区
修改2021-07-12 09:46:19
3280
修改2021-07-12 09:46:19
举报
文章被收录于专栏:java大数据java大数据

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

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档