使用request对象进行数据传递

在进行请求转发时,需要把一些数据传递到转发后的页面进行处理,需要使用request对象的setAttribute方法将数据保存到request范围内的变量中

使用:

request对象可以视为一个域,可以应用setAttribute()方法向域范围内存放数据
request对象的setAttribute()方法的格式:
request.setAttribute(String name,Object object);
参数说明
name:变量名,为String类型,
object:用于指定需要在request范围内传递的数据,为Object类型
在将数据保存到request范围内的变量中后,可以通过request对象的getAttribute()方法获取该变量的值:
request.getAttribute(String name);
在这里插入图片描述
创建index.jsp文件,首先应用Java的try…catch语句捕获页面中的异常信息,若没有异常,将运行结果保存到request范围内的变量中;若出现异常,将错误信息保存到request范围内的变量中,再应用jsp:forward将页面转发到deal1.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>
<%
try{											//捕获异常信息
	int money=100;
	int number=0;
	request.setAttribute("result",money/number);//保存执行结果
}catch(Exception e){
	request.setAttribute("result","很抱歉,页面产生错误!!");	//保存错误提示信息
}
%>
<jsp:forward page="deal1.jsp"></jsp:forward>
</body>
</html>

创建deal1.jsp文件,在该文件中通过request对象的getAttribute()方法获取保存在request范围内的变量result并输出,由于getAttribute()方法的返回值为Object类型,所以需要调用其toString()方法将其转换为字符串类型

<%@ 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 message=request.getAttribute("result").toString();
%>
<%=message %>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44234912/article/details/87902281