JSP之request对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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对象的主要内容,如果未能解决你的问题,请参考以下文章

JSP之request对象

JAVA-JSP内置对象之request范围

Jsp获取Java的对象(JavaBean)

JAVA-JSP内置对象之request对象的其他方法

JSP之application对象

JAVA-JSP内置对象之request获得所有的参数名称