客户端在第一次请求服务端时,如果服务端发现此请求没有JSESSIONID,则会创建一个拥有JSESSIONID的cookie,并返回给客户端
Cookie:
a、不是内置对象,要使用必须new
b、但是服务端会自动生成一个name=JSESSIONID的cookie,并返回客户端
四种范围对象
(小 --> 大)
pageContext JSP页面容器:当前页面有效
request 请求对象:同一次请求有效,其他请求无效(请求转发有效,重定向无效)
session 会话对象:同一次会话有效(无论怎么跳转都有效,关闭/切换浏览器无效:从登录->退出全部有效)
application 全局对象:全局有效(整个项目有效,切换浏览器仍然有效,但关闭服务、切换其他项目时无效)
以上对象共有的方法:
Object getAttribute(String name):根据属性名,获取属性值
void setAttribute(String name,Object obj):设置值属性值(新增/修改)
例:setAttribute(“a”,“b”):如果a对象之前不存在,则新建一个a对象,并把a赋值为b,如果a对象之前存在,把a赋值为b
void removeAttri(String name):根据属性名,删除对象
示例代码:
pageContext.jsp
<%
pageContext.setAttribute("hello", "world");
%>
<%=//pageContext只在当前页面有效,跳转无效
pageContext.getAttribute("hello")
%>
request.jsp
<%
request.setAttribute("hello", "world");
//只有请求转发跳转才能实现对象共享
request.getRequestDispatcher("rq.jsp").forward(request,response);
//重定向跳转不行,因为重定向需要两次请求
//response.sendRedirect("rq.jsp");
%>
rq.jsp
<%=
request.getAttribute("hello")
%>
session.jsp
<%
session.setAttribute("hello","world");
request.getRequestDispatcher("ss.jsp").forward(request,response);
%>
ss.jsp
<%=
session.getAttribute("hello")
%>
application.jsp
<%
application.setAttribute("hello","world");
request.getRequestDispatcher("ap.jsp").forward(request,response);
%>
ap.jsp
<%=
application.getAttribute("hello")
%>
总结
1、以上的4个范围对象,通过setAttribute()赋值,通过getAttribute()取值;
2、以上范围对象,尽量使用最小的范围,因为范围越大,造成的性能损耗越大。