JSP之request对象

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

示例:创建index.jsp文件,使用Java中的try……catch语句捕获异常,将数据保存到request范围内的变量中:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
     <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <%
    try{
    int a=1;
    int b=0;
    request.setAttribute("result", a/b);
    }catch(Exception e){
    request.setAttribute("result", "很抱歉,页面发生错误!");    
    }
     %>
     <jsp:forward page="MyJsp.jsp"></jsp:forward>
  </body>
</html>

然后用 <jsp:forward>动作将指令转发到MyJsp.jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'MyJsp.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
  <%String message=request.getAttribute("result").toString(); %>
  <%=message %>
  </body>
</html>

run:

很抱歉,页面发生错误! 

  

你可能感兴趣的:(JSP之request对象)