【JavaWeb】 JSP九大内置对象和四大作用域

2022-07-28,,,,

JSP九大内置对象

无需new也能使用的对象


一 : out 输出对象

out : 输出对象,向客户端输出内容


二:request 请求对象

request:请求对象;存储“客户端向服务端发送的请求信息”

常见方法:

1:String getParamter(String name) :
          根据请求的字段名key,返回字段值value. (name->value)

2:String[ ] getParamterValues(String name) :
         根据请求的字段名key,返回多个字段值value.

3: void setCharacterEncoding("编码格式utf-8"):
         设置请求编码

4: request.getRequestDispatcher("b.jsp").forword(request,response):
         请求转发的方式跳转页面 A->B

5: ServletContext getSeverContext():
         获取项目的ServletContext对象

练习 :

(注册页面 Register.jsp -> 展示注册信息 show.jsp)

Register.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<form action="show.jsp" method="post">
			用户名:<input type="text" name="uname"/><br/>
			密码&nbsp;&nbsp;&nbsp;&nbsp;<input type="password" name="upwd"/><br/>
			年龄&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="uage"/><br/>
			爱好&nbsp;&nbsp;&nbsp;<br/>
			<input type="checkbox" name="uhobbies" value="篮球"/>篮球
			<input type="checkbox" name="uhobbies" value="足球"/>足球
			<input type="checkbox" name="uhobbies" value="乒乓球"/>乒乓球<br/>
			<input type="submit" name="注册" />
		</form>
</body>
</html>

show.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		//设置post编码utf-8(只对post有效)
		request.setCharacterEncoding("utf-8"); 
		
		String name = request.getParameter("uname");
		
		String pwd = request.getParameter("upwd");
		
		int age = Integer.parseInt( request.getParameter("uage") );
		
		String[] hobbies = request.getParameterValues("uhobbies");
	%>
	注册成功!!! <br>
	注册信息如下: <br>
	用户名:<%=name %> <br/>
	密码:<%=pwd %>  <br/>
	年龄:<%=age %>  <br/>
	爱好:
			<%
				if(hobbies != null){
					for(String hobby:hobbies){
						out.print(hobby+" ");
					}
				}
			%>
</body>
</html>

运行结果:


三: response 响应对象

response : 响应对象

常见方法:

1: void addCookie(Cookie cookie):
         服务端向客户端增加cookie对象

2: void sendRedirect(String location)throws IOException :
         页面跳转的一种方式 (重定向)

3: void setContentType(String type) : 设置服务端响应的编码 (设置服务端的ContentType类型)

练习 :

login.jsp(登录) -> check.jsp(检查) -> success.jsp(登录成功)

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="check.jsp" method="post">
		用户名:<input type="text" name="uname"><br/>
		密码&nbsp;&nbsp;&nbsp;&nbsp;<input type="password" name="upwd"><br/>
		<input type="submit" value="登录"><br/>
	</form>
</body>
</html>

check.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<%
			request.setCharacterEncoding("utf-8");
			
			String name = request.getParameter("uname");
			
			String pwd = request.getParameter("upwd");
			
			if(name.equals("admin") && pwd.equals("123456")){
				response.sendRedirect("success.jsp"); //重定向:导致数据丢失 name为null
				
				//页面跳转:请求转发,可以获取数据,但是地址栏没有改变(仍然保留 转发之前的地址)
				//request.getRequestDispatcher("success.jsp").forward(request, response);
			}else{
				out.print("用户名或密码错误!");
			}
		%>
</body>
</html>

success.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	登录成功!! <br/>
	欢迎您:
		<%
			String name = request.getParameter("uname");
			out.print(name);
		%>
</body>
</html>

response 重定向 运行结果:
(地址栏改变,但不保留第一次请求时的数据,两次请求)

客户端 ➡ 服务A (服务端) ➡ 客户端

客户端 ➡ 服务B (服务端)

跳转发生的位置 : 客户端发出的第二次跳转


request 请求转发 运行结果:
(地址栏不改变,但保留第一次请求时的数据,一次请求)

客户端 ➡ 【服务A ➡ 服务B】(服务端)

跳转发生的位置 : 服务端


四 : session 会话对象

( 和 cookie 一起学 ,先写的 cookie 内容)

session (服务端 保存的内容为Object类型)

Cookie (客户端,不是内置对象 保存的内容为String类型):
       Cookie由服务端生成的,再发送给客户端保存


cookie作用 :

本地缓存,提高访问服务端的效率,但安全性较差。
(例如听歌第一次听需要缓存,再听则无需缓存,直接听)

包:javax.servlet.http.Cookie

cookie常用方法:

public Cookie(String name,String value)

String getName() : 获取name

String getValue() : 获取value

void setMaxAge(int expiry) ; 最大有效期(秒)


cookie 过程:

1:服务端准备Cookie: response.addCookie(Cookie cookie)

2:页面跳转 (转发,重定向)

3:客户端获取Cookie: request.getCookies();

(1):服务端增加cookie:response对象;
      客户端获取对象:request对象;

(2):不能直接获取某一个单独对象,只能一次性将全部的cookie拿到


cookie 练习1 :

(模拟服务端生成cookie,客户端接收cookie)

服务端 response.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<%
			//服务端 生成cookie
			Cookie cookie1 = new Cookie("name","zs");
			Cookie cookie2 = new Cookie("pwd","123");
			
			response.addCookie(cookie1);
			response.addCookie(cookie2);
			
			//页面跳转到客户端  (转发 , 重定向) 此处为重定向
			response.sendRedirect("result.jsp");
		%>
</body>
</html>

客户端 result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<%
			//客户端 接收cookie
			Cookie[] cookies = request.getCookies();
			
			//展示内容
			for(Cookie cookie : cookies){
				out.print(cookie.getName() + "--" + cookie.getValue() + "<br/>");
			}
		%>
</body>
</html>

运行结果:

通过运行结果,发现自动生成一个 JSESSIONID的cookie.


cookie 练习2 :

( 使用cookie实现记住 用户名和密码 功能 )

客户端 login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<%!
			//全局变量
			String name;
			String pwd;
		%>
		
		<%
			//相当于客户端
			
			Cookie[] cookies = request.getCookies();
			if(cookies != null){
				for(Cookie cookie : cookies){
					if(cookie.getName().equals("uname")){
						name = cookie.getValue();
					}
					if(cookie.getName().equals("upwd")){
						pwd = cookie.getValue();
					}
				}
			}
		%>
		
	<form action="remember.jsp" method="post">
		用户名:<input type="text" name="uname" value=<%=name==null?"":name%>><br/>
		密码&nbsp;&nbsp;&nbsp;&nbsp;:<input type="password" name="upwd" value=<%=pwd==null?"":pwd%>><br/>
		<input type="submit" value="登录"><br/>
	</form>
</body>
</html>


服务端 remember.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<%
			//相当于服务器
			
			//设置编码
			request.setCharacterEncoding("utf-8");
			
			//获取用户名和密码
			String name = request.getParameter("uname");
			String pwd = request.getParameter("upwd");
			
			//新建cookie
			Cookie cookie1 = new Cookie("uname",name);
			Cookie cookie2 = new Cookie("upwd",pwd);
			
			//服务端向客户端增加cookie对象
			response.addCookie(cookie1);
			response.addCookie(cookie2);
			
			//重定向 把cookie发送给客户端
			response.sendRedirect("aaa.jsp");
		%>
</body>
</html>

客户端的另一个jsp文件 aaa.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		客户端的另一个jsp文件<br/>
		登录成功!
</body>
</html>

最后,再次运行login.jsp时,用户名和密码已经输入。


(session 内容)

session 作用:

在一段时间内保存用户的状态(信息)


session机制:

1: (解释cookie中存在的JSESSIONID):
        客户端请求服务端时,服务端会产生一个session对象,每个session对象都有唯一的sessionID(用于区分其他session),同时服务器会产生一个cookie.         该cookie的key="JSESSIONID",value="sessionID"。然后,服务器在响应客户端的同时,将该cookie发送给客户端,所以客户端就有了一个cookie(JSESSIONID);
        在一段时间内,客户端再次请求服务端时,服务端会先在服务端的session中用sessionID来匹配客户端的JSESSIONID,若匹配成功,则说明该客户端之前访问过,无需再分配ID,故无需再次登录信息等。
(比如成功登陆了某网站后,一段时间内无需再次登录)

2: session存储在服务端

3: session是在同一个用户(客户)请求时共享(无需再登)


session方法:

1: getid() : 获取 sessionid

2: boolean isNew() : 判断是否是新用户(第一次访问)

3: void invalidate() : 使session失效 ( 退出登录,注销等)

4: void setAttribute() : 设置指定名称的session属性值。

5: object getAttribute() : 获取与指定名字相关联的session属性值。

6:void setMaxInactiveInterval(秒) : 设置最大有效不活动时间

7: int getMaxInactiveInterval() : 获取最大有效不活动时间


练习:

测试登录,最大有效不活动时间,使session失效功能等

login.jsp (登陆界面):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="check.jsp" method="post">
		用户名:<input type="text" name="uname"><br/>
		密码&nbsp;&nbsp;&nbsp;&nbsp;<input type="password" name="upwd"><br/>
		<input type="submit" value="登录"><br/>
	</form>
</body>
</html>

check.jsp (检查用户名密码是否正确):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<%
			request.setCharacterEncoding("utf-8");
			
			String name = request.getParameter("uname");
			
			String pwd = request.getParameter("upwd");
			
			if(name.equals("admin") && pwd.equals("123456")){
				// 登陆成功
				session.setAttribute("name", name);
				session.setAttribute("pwd", pwd);
				//在控制台查看sessionID
				System.out.println("sessionID: "+session.getId());
				
				//请求转发 到登陆成功欢迎界面
				request.getRequestDispatcher("welcome.jsp").forward(request,response);
			}else{
				// 登陆失败! 重定向到登录界面:重新登录
				response.sendRedirect("login.jsp");
			}
		%>
</body>
</html>

welcome.jsp (登陆成功):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	登陆成功!<br/>
	欢迎您:
	<%	
		//设置最大有效不活动时间为10s
		//session.setMaxInactiveInterval(10);
		
		//得到name的属性值
		String name = (String)session.getAttribute("name");
		
		//没有登录 或者 超过最大有效不活动时间,name为null
		if(name==null){ 
			// 重定位到login.jsp进行重新登陆
			response.sendRedirect("login.jsp"); 
		}else {
			out.print(name);
		}
	%>
	<br/>
	<a href="invalidate.jsp">注销账号</a>
</body>
</html>

invalidate.jsp (注销):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<%
			//实现注销账户功能
			
			//使当前session失效 
			session.invalidate();
			
			//回到登录界面
			response.sendRedirect("login.jsp");
		%>
</body>
</html>

aaa.jsp (客户端的另一个jsp文件):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		//找到服务端自动生成并响应给客户端的JSESSIONID
		Cookie[] cookies = request.getCookies();
		
		for(Cookie cookie:cookies){
			if(cookie.getName().equals("JSESSIONID")){
				System.out.println("JSESSIONID: "+cookie.getValue());
			}
		}
	%>
</body>
</html>

运行结果:



sessionID 和 JSESSIONID一致

在控制台中可以看到 客户端的JSESSIONID和服务端的sessionID是一致的。


ps: 测试最大有效不活动时间时,将地址栏变为welcome测试,因为请求转发不改变地址栏。(或者直接将跳转到welcome.jsp的方式改为重定向)


session总结:

session 与 cookie 的区别:
1:session 为内置对象,cookie 不是内置对象(需要new)
2:session 保存在服务端,cookie 保存在客户端
3:session 保存的 value 为 object 类型,cookie 的value为String类型
4:session 较为安全,cookie 较不安全


五 : application 应用对象

常用方法:

1:String getContextPath() : 获取虚拟路径
2:String getRealPath( String Contextpath) : 获取虚拟路径所对应的绝对路径


练习:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	  <%= "当前项目的虚拟路径: "+application.getContextPath() %><br/>
	  <%= "当前项目的绝对路径: "+application.getRealPath("/MyjspProject") %>
</body>
</html>

运行结果:


六 : page 页面对象

类似于 this,指向当前 jsp 程序


七 : pageContext 页面上下文对象

pageContetx对象是jsp页面中所有对象功能的最大集成着。


八 : exception 异常对象

exception对象用来处理jsp文件执行时发生的所有异常和错误,只有在page指令中设置isErrorPage的属性值为true的页面中才可以使用

页面指令:<%@page isErrorPage=“true”%>


九 : config 配置对象

config 对象表示当前jsp的配置文件,获取服务器配置信息


JSP四大作用域:

四种范围对象 (小➡大):

page范围 ( 仅在当前页面有效 ):

(response响应对象,page页面对象,pageContext页面上下文对象,out输出对象,config配置对象,exception异常对象)

当前页面有效,页面跳转后就无效。


request 范围 ( 同一次请求有效 ):

(request请求对象)

请求转发后有效,重定向后则无效(因为重定向有两次请求)


session 范围 ( 同一次会话有效 ):

(session会话对象)

同一次会话有效,可以任意跳转页面都有效,直到关闭浏览器或者切换浏览器后无效 (session在服务端,切换浏览器后,服务端改变)。

【一次会话:从登录(某网站)➡退出 或者 打开(浏览器)➡关闭】


application范围 ( 全局有效,当前项目有效):

(appication全局(应用)对象)

在当前项目下都有效,任意跳转页面,任意更换浏览器均有效。直到关闭了服务 (tomcat)才失效


四种对象共有方法:

1: Object getAttribute(String name) : 根据属性名,获取属性值

2:void setAttribute(String name,Object obj) : 设置属性值 (新增和修改) 【name不存在,则新建;name已存在,则修改】

3: void removeAttribute(String name): 根据属性名,删除对象

本文地址:https://blog.csdn.net/weixin_45260385/article/details/109255136

《【JavaWeb】 JSP九大内置对象和四大作用域.doc》

下载本文的Word格式文档,以方便收藏与打印。