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:

    很抱歉,页面发生错误! 
    不努力,还要青春干什么?
  • 相关阅读:
    用asp自编源码制作动态的音乐播放页面
    VBS 连接数据库 样例
    VBS访问SQL数据库
    人人都应该知道的计算机网络协议(1)
    VBS 访问数据库 别人写的一份公共函数
    WPF DateTimePicker 和 TimeSpanPicker 控件发布
    实现Evernote的OAuth授权
    EvernoteTodo发布
    EvernoteAdage 发布
    关于 极限(Extreme)
  • 原文地址:https://www.cnblogs.com/caidupingblogs/p/5227593.html
Copyright © 2011-2022 走看看