JSP九大内置对象
- PageContext 存东西
- Request 存东西
- Response
- Session 存东西
- Application 【ServletContext】存东西
- config 【ServletConfig】
- out
- page
- exception
JSP作用域理解
有三个电脑去访问一个网站,这里有一个网站服务器,每个人用浏览器得到一个page
page的范围是最小的,page上面发送请求给服务器,但是请求可以转发,也就是request
转发到的其他页面也有效,所以请求的作用域比page大。
每个人对应服务器有一个Session,如果想创建一个需求让三个人都访问(如统计在线人数),这时候
就要用Application(ServletContext)
这里面其实不同的页面也可以访问到其他页面的Session中存储的数据,他们也都能访问到application中存的数据
那么Session和application的区别是什么的?
Session和application
- session其实是标记了你的请求来自哪个浏览器,如果重启了浏览器 session ID就变了,数据就没了
- 如果一直不存储浏览器,根据session设定的保存时间,当时间到了也会销毁
- appication是在整个项目中,只有关闭tomcat服务器,application才会被销毁
- session对每个用户是单独的,applicatio是所有用户(浏览器)共享的
JVM双亲委派机制:
前端转发和后端转发的对比
场景理解
request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,下次点击来就是新的新闻
session:产生的数据用户用完一会还有用,比如购物车;
application:产生的数据,一个用户用完了其他用户还可能使用,比如聊天数据,统计在线人数
find是逐层寻找的,寻找顺序:page->request->session->application
pageContext.setAttribute("name1","秦疆1号");//保存的数据只在一个页面中有效
2 request.setAttribute("name2","秦疆2号");//保存的数据只在一次请求中有效,请求转发会携
带这个数据
3 session.setAttribute("name3","秦疆3号");//保存的数据只在一次会话中有效,从打开浏览器
到关闭浏览器
4 application.setAttribute("name4","秦疆4号"); //保存的数据只在服务器中有效,从打开服
务器到关闭服务器
实现demo 通过不同的写法对jsp取值进行测试
PageContextDemo01.jsp
<%--
Created by IntelliJ IDEA.
User: apple
Date: 2021/10/31
Time: 10:17 AM
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.setAttribute("name1","lding1");//保存的数据只在一个页面中有效
request.setAttribute("name2","lding2");//保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","lding3");//保存的数据中只在一个会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","lding4");//保存的数据在服务器中有效,从打开服务器到关闭服务器
%>
<%--取东西--%>
<%
// pageContext.getAttribute();
// request.getAttribute();
//从底层到高层(作用域)
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>
<%
pageContext.forward("page2.jsp");
%>
</body>
</html>
前端页面转发和后端页面转发的对比
前端直接使用pageContext.forward进行转发即可
pageContext.forward("/index.jsp");
request.getRequestDispatcher("/index.jsp").forward(request,response);