zoukankan      html  css  js  c++  java
  • 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:

    很抱歉,页面发生错误! 
    不努力,还要青春干什么?
  • 相关阅读:
    HDU ACM 1392 Surround the Trees-&gt;凸包
    JMeter使用记录1 -- JDBC測试
    Html学习笔记4
    c++使用mysql的api连接相关问题
    [Angularjs]ng-select和ng-options
    mysql之字符串操作
    mysql之日期函数
    [sharepoint]Rest api相关知识(转)
    [工具类]泛型集合转换为DataTable
    C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
  • 原文地址:https://www.cnblogs.com/caidupingblogs/p/5227593.html
Copyright © 2011-2022 走看看