JavaWeb18(JSP内置对象及其作用域)

九大内置对象

  • PageContext (可以存东西)
  • Request (可以存东西)
  • Response
  • Session (可以存东西)
  • Application (ServletContext) (可以存东西)
  • config (ServletConfig)
  • out
  • page (基本不使用)
  • exception

存取数据示例

pageContextDemo01

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--存数据--%>
<%
    pageContext.setAttribute("name1","源浩");//保存的数据只在该页面中有效
    request.setAttribute("name2","袁浩");//保存的数据只在一次请求中有效,请求转发后也会携带该数据
    session.setAttribute("name3","元浩");//保存的数据只在一次会话中有效,从浏览器打开到关闭
    application.setAttribute("name4","援耗");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
%>

<%--取数据(一般用什么存就用什么取,这里为了学习统一用pageContext取出数据)--%>
<%
    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表达式输出(自动过滤)--%>
<h1>取出的数据为:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
</body>
</html>

访问测试
在这里插入图片描述

前后端页面跳转代码

pageContextDemo03

<%--
  Created by IntelliJ IDEA.
  User: 15983
  Date: 2021/8/10
  Time: 23:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--请求转发--%>
<%
    //前端代码
    pageContext.forward("/index.jsp");
    //后台代码
    //request.getRequestDispatcher("/index.jsp").forward(request,response);
%>
</body>
</html>

测试访问
在这里插入图片描述

常用内置对象作用域

  • request:一般存放用户只看一次的信息,比如广告
  • session:一般存放用户会再次使用的信息,比如购物车信息,登录信息
  • application:可能存放多个用户同时使用的信息,比如聊天记录

猜你喜欢

转载自blog.csdn.net/qq_51224492/article/details/119578302