【学习笔记】JSP内置对象

JSP内置对象

  • pageContext

  • Request

  • Response

  • config [ServletConfig]

  • out

  • Application [ServletContext]

  • page

  • exception

  • session

 

其中,pageContext、Request、Application、session 用于存储数据

它们都使用setAttribute() 来存数据

<%
    pageContext.setAttribute("name1","张三");
    request.setAttribute("name2","李四");
    session.setAttribute("name3","王五");
    application.setAttribute("name4","赵六");
%>

取数据,我们使用pageContext.findAttribute() 通过寻找的方式来取数据

是从底层到高层,也就是作用域从小到大

<%
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3 = (String) pageContext.findAttribute("name3");
    String name4 = (String)pageContext.findAttribute("name4");
    String name5 = (String) pageContext.findAttribute("name5");
%>

输出,使用EL表达式 ${}

<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>

另一种输出方式就是:使用jsp表达式 <%=xxx%>

这两种输出方式的区别是:

当一个没有值的 变量 被输出时,如 name5,${name5} 什么都不输出,{%=name5%}会输出null

这四个内置对象的作用域

  • pageContext:保存的数据只在一个页面中有效

  • request:保存的数据在一次请求中有效,请求转发会携带这个数据

  • session:保存的数据在一次会话中有效

  • application:保存的数据在服务器中有效,从打开服务器到关闭服务器

 

我们现在从另一个页面中,取数据,来查看它们的作用域

image-20221021162012864

可以发现,我们只能取出session 和 application 中的数据,因为这是在一个新的页面,所以pageContext是绝对取不到的,我们也没有进行请求转发,所以request也取不到。

 

请求转发:

<%
    pageContext.forward("/jspDemo02.jsp");
%>

我们把jspDemo01.jsp 转发到 jspDemo02.jsp,然后再request 中存的数据,也被携带到jspDemo02.jsp,在这个页面取数据,就可以取到了

pageContext.forward("/jspDemo02.jsp") 相当于 request.getRequestDispatcher("/jspDemo2.jsp").forward(request,response);

 

除此之外,如果我们想让pageContext存的数据也能在其他页面被取到,可以使用 setAttribute() 的重载方法

image-20221021163347210

public void setAttribute(String name, Object attribute, int scope) {
    switch(scope) {
    case 1:
        this.mPage.put(name, attribute);
        break;
    case 2:
        this.mRequest.put(name, attribute);
        break;
    case 3:
        this.mSession.put(name, attribute);
        break;
    case 4:
        this.mApp.put(name, attribute);
        break;
    default:
        throw new IllegalArgumentException("Bad scope " + scope);
    }
​
}

前两个参数和之前相同是键和值,第三个参数是作用域

public static final int PAGE_SCOPE = 1;
public static final int REQUEST_SCOPE = 2;
public static final int SESSION_SCOPE = 3;
public static final int APPLICATION_SCOPE = 4;

在PageContext 抽象类中,定义了四个常量,这四个常量就是作用域,分别对应了 pageContext、request、session、application 的作用域

<%
    pageContext.setAttribute("city","beijing",PageContext.APPLICATION_SCOPE);
    //相当于 application.setAttribute("city","beijing")
%>

然后就可以从其他的页面去取数据了,其他几个与之类似

posted @ 2022-10-21 16:44  GrowthRoad  阅读(20)  评论(0编辑  收藏  举报