第6章 JSP的内置对象

为了简化jsp应用程序开发,jsp2.0规范中定义了9种内置对象,在jsp不需要预先声明和创建就能直接使用。jsp内置对象有out、page、request、response、seesion、pageContext、config、exception和application对象

本章主要内容

     1.内置对象介绍

     2.内置对象实例

6.1 out对象的方法

      out对象主要用来向客户输出各种数据类型的内容,并管理应用服务器上的输出缓冲区(buffer)。缓冲区默认值是8KB,可以通过page指令来改变缓冲区的大小

      Out对象被封装成javax.servlet.jsp.JspWriter 接口。它表示为客户打开的输出流(output stream),PrintWriter使用它向客户端发送输出流

      ou对象的主要方法如下:

       1.print()/println():用于输出数据。Out对象是JSP中使用最为频繁的对象,它的print()和println()方法最常用。print()方法把Java对象原始数据类型输入到客户端的缓冲区,

          而println()方法除了把内容输出到客户端,还在后面添加一个空行。

       2.newLine()方法:用于输出一个换行字符。

       3.flush():用于输出缓冲区里的数据。此方法会先将之前缓冲区中的数据输出至客户端,然后再清除缓冲区中的数据。

       4.clearBuffer():用于清除缓冲区里的数据,并把数据输出到客户端。

       5.clear():用于清除缓冲区里的数据,但不会把数据输出到客户端。

       6.getBufferSize():用于获得缓冲区的大小。

       7.getRemaining():用于获得缓冲区中没有被占用的空间的大小。

       8.isAutoFlush():返回布尔值,如果AutoFlush为真,则返回true,反之,返回false。

       9.close():关闭输出流.可以强制终止当前页面的剩余部分向浏览器输出。

       6.1.2 out对象实例

          例6-1 out对象实例(outexamples1.jsp)

<%@page contentType="text/html" 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>out对象实例演示</title>
</head>
<body>
<PRE>
<% for(int i=0;i<2;i++)
{ out.println("<h5>中国欢迎你!</h5>"); }
%>
<%
boolean b = true;
char c = 'X';
double d = 0.66;
float f = 1;
int i = 2;
long l = 3;
String str = "你好!";
out.println(b);
out.print(c);
out.newLine();
out.println(d);
out.println(f);
out.println(i);
out.println(l);
out.print(str);
out.println(123);
out.println(456);
%>
</PRE>
</body>
</html>
例6-2 out对象实例2(outExamples2.jsp)

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>out对象实例演示</title>
    </head>
    <body>
        缓存大小:<%=out.getBufferSize()%><br>
       剩余缓存大小:<%=out.getRemaining()%><br>
        自动刷新:<%=out.isAutoFlush()%><br>
        <hr>
        <%
            out.print("中国欢迎你,北京欢迎你!<br>");
            out.print("当前可用缓冲区空间:" + out.getRemaining() + "<br>");
            out.print("<font color='red'>接着调用out.flush()方法</font><br>");
            out.flush();//注释掉是另一个效果
            out.print("当前可用缓冲区空间:" + out.getRemaining()+ "<br>");
            out.clearBuffer();
            out.print("当前可用缓冲区空间:" + out.getRemaining()+ "<br>");
            out.flush();
        %>
    </body>
</html>

image
 

6.2page对象

         page对象代表JSP本身,更准确地说它代表JSP被转译后的Servlet,它可以调用Servlet类所定义的方法。

         page对象指向当前JSP页面本身,有点象类中的this指针,它是java.lang.Object类的实例。

         目前,page对象很少使用,它是为了指定其它的脚本语言而保留的,Java是唯一的JSP脚本语言。

6.3 request对象

          request对象实现httpservletrequest接口,使用httpservletRequest接口的方法很方便地取得客户端各种信息  ,request对象的生命周期由jsp容器自动控制。当客户端通过

          http协议请求一个jsp页面时,jsp容器就会创建request对象并将请求信息包装到request对象中;当jsp容器处理完请求后,request对象就会自动销毁

          6.3.1 request对象的方法

                 当用户请求一个JSP页面时, JSP页面所在的Tomcat服务器将用户的请求封装在内置对象request中。request内置对象代表了客户端的请求信息,主要用于接收客户端通

                 过HTTP协议传送给服务器端的数据。在客户端的请求中如果有参数,则该对象就有一个参数列表。它通常是HttpServletRequest的子类,其作用域就是一次request请

                求。Servlet容器将客户端信息封装在一个代表客户端的request对象中,该对象是 javax.servlet.ServletRequest的子类型。封装了HttpServletRequest对象中的客户

                端信息包括请求头(Header)、系统信息(比如编码方式〉、请求方式(比如get或post)、请求参数信息、Cookie和其它信息。该对象调用相应的方法可以获取封装的信息,也

                就是说,使用该对象可以获取用户浏览器提交的请求信息,以便做出相应的响应。

request对象的主要方法如下:

1.getAttribute(String name):用于返回name指定的属性值,若不存在指定的属性,就返回null。

2.getAttributes():用于返回request对象的所有属性的名字集合,结果集是一个Enumeration(枚举)类的实例。

3.getCookies() :用于返回客户端的所有Cookie对象,结果是一个Cookie数组。

4.getCharacterEncoding(): 返回请求中的字符编码方式。

5.getContentLength():以字节为单位返回客户端请求的大小。如果无法得到该请求的大小,则返回-1。

6.getHeader(String name):用于获得HTTP协议定义的文件头信息。

7.getHeaders(String name) :用于返回指定名字的request Header的所有值,其结果是一个Enumeration类的实例。

8.getHeaderNames():用于返回所有request Header的名字,其结果是一个Enumeration类的实例。

9.getInputStream():用于返回请求的输入流,获得请求中的数据。

10.getMethod():用于获得客户端向服务器端传送数据的方法,如GET,POST,HEADER,TRACE等。

11.getParameter(String name) :用于获得客户端传送给服务器端的参数值。获取表单提交的信息,以字符串形式返回客户端传来的某一个请求参数的值,该参数名由name指定。当传递给此方法的参数名没有实际参数与之对应时,返回null。

12.getParameterNames():用于获得客户端传送给服务器端的所有参数名字,其结果是一个Enumeration类的实例。

13.getParameterValues(String name) :用于获得指定参数的所有值。返回客户端传送给服务器端的所有参数名,结果集是一个Enumeration类的实例。当传递给此方法的参数名没有实际参数与之对应时,返回null。

14.getProtocol():用于获取客户端向服务器端传送数据所依据的协议名称。

15.getQueryString():用于获得查询字符串,该字符串是由客户端以GET方式向服务器端传送的。

16.getRequestURI():用于获取发出请求字符串的客户端地址。

17.getRemoteAddr():用于获取客户端IP地址。

18.getRemoteHost():用于获取客户端名字。

19.getSession([Boolean create]) :用于返回和请求相关的session。create参数是可选的。当有参数create且这个参数值为true时,如果客户端还没有创建session,那么将创建一个新的session。

20.getServerName():用于获取服务器的名字。

21.getServletPath():用于获取客户端所请求的脚本文件的文件路径。

22.getServerPort():用于获取服务器的端口号。

23.removeAttribute(String name) :用于删除请求中的一个属性。

23.setAttribute(String name, java.lang.Object obj) :用于设置request的参数值。

例6-4 requset对象实例(requestExamples1.jsp)

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>request对象实例演示</title>
    </head>
    <body>
        <%
            request.setAttribute("Variable1","123");
            request.setAttribute("Variable2","456");
            request.setAttribute("Variable3","789");
            Enumeration e=request.getAttributeNames();
          
            while(e.hasMoreElements()) {
                String attributeName=(String)e.nextElement();
                String attributeValue=(String)request.getAttribute(attributeName);
                out.print("变量名称:"+attributeName+" &nbsp &nbsp");
                out.print("变量内容:"+attributeValue+"<BR>");
            }
          %>
    </body>
</html>

image

本例主要对setAttribute()、getattributeName()和getAttribute()方法使用进行演示

例6-5 request对象实例2(requestExamples2.jsp和requestExamples.jsp)

requestExamples2.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
        <title>request对象实例演示</title>
    </head>
    <body>
        <form action=" requestExamples.jsp" method="post">
            <p>数据1
            <input type="text" name="Variable1" >
            <p>数据2
            <input type="text" name="Variable2" >
            <p>数据3
            <input type="text" name="Variable3" >
            <p>数据4
            <input type="text" name="Variable4">
            <p>数据5
            <input type="text" name="Variable5">
            <p>数据6
            <input type="text" name="Variable6" >
            <br>
            <input type="submit" value="提交">
            <input type="reset" value="清除">
        </form>
       
    </body>
</html>

 

requsetExamples.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.*"%>
<!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>request对象实例演示</title>
    </head>
    <body>
        <hr>
        <h3>刚才输入的6个数据是:</h3>
        <%
            Enumeration e=request.getParameterNames();
            while(e.hasMoreElements()){
                String parameterName=(String)e.nextElement();
                String parameterValue=(String)request.getParameter(parameterName);
                out.print("参数名称:"+parameterName+"<br>");
                out.print("参数内容:"+parameterValue+"<br>");
}
        %>
        <hr>
    </body>
</html

image              image 

本例是对getParameter()方法和getparameterNames()方法的使用进行演示

例6-6 request对象实例3(requestEample3.jsp和requestExample31.jsp)

requestEample3.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>request对象实例演示</title>
    </head>
    <body>
       <form method="post" action="requestExamples31.jsp" >
        <p>文本内容<input type="text" name="text"></p>
        <p>整数类型<input type="text" name="integer"></p>
        <p>复选框:</p>
        <p>1.<input type="checkbox" name="checkbox1" value="1"><br>
        2.<input type="checkbox" name="checkbox2" value="1">
        </p>
        <p>单选按钮:
        <input type="radio" name="radiobutton" value="1">
        <input type="radio" name="radiobutton" value="2">
        <input type="radio" name="radiobutton" value="3">
        <input type="radio" name="radiobutton" value="4">
        <input type="radio" name="radiobutton" value="5">
        <input type="radio" name="radiobutton" value="6">
        </p>
        <p>下拉列表:
        <select name="select">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
        </select>
        </p>
        <p><input type="submit" name="submit" value="提交"></p>
       </form>
    </body>
</html>

requestExample31.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>request对象实例演示</title>
    </head>
    <body>
      <%
        String strText,strInteger,strCheckbox1,strCheckbox2;
        String strRadiobutton,strSelect,strOut,errOut;
        Integer intInteger;
        int errsCount;
        Vector errs =new Vector();
        strText=request.getParameter("text");
        //得到并处理名为text的文本输入
        if(strText.length()==0){
        //向错误信息库中添加信息
            errs.addElement(new String("文本内容域没有值输入"));
        }
        strInteger=request.getParameter("integer");
        //得到名为Integer的输入并转化为Integer,同时检查是否为数值
        try{
            intInteger=Integer.valueOf(strInteger);
        }catch(NumberFormatException e){
            errs.addElement(new String("整数类型需要输入数字!"));
             //向错误信息库中添加信息
            intInteger=new Integer(0);
            //设为缺省值
            }
        strCheckbox1=request.getParameter("checkbox1");
        strCheckbox2=request.getParameter("checkbox2");
        //得到CheckBox的输入
        if(strCheckbox1==null){
            strCheckbox1="没有被选中";
        }else
        {
            strCheckbox1="被选中";
        }
        if(strCheckbox2==null){
            strCheckbox2="没有被选中";
        }else
        {
            strCheckbox2="被选中";
        }
        strRadiobutton=request.getParameter("radionbutton");
        //得到radiobutton的输入
        if(strRadiobutton==null){
            errs.addElement(new String("单选按钮没有输入!"));
            strRadiobutton="没有输入";
        }
       
        //得到select的输入:
        strSelect=request.getParameter("select");
        strOut="文本内容的值是:"+strText;
        strOut+="<br>整数类型的值是:"+intInteger;
        strOut+="<br>复选框1"+strCheckbox1;
        strOut+="<br>复选框2"+strCheckbox2;
        strOut+="<br>单选按钮的值是:"+strRadiobutton;
        strOut+="<br>下拉列表的值是:"+strSelect+"<br>";
        //输出结果
        errsCount=errs.size();
        errOut=new String("");
        //输出错误
        for(int i=0;i<errsCount;i++){
            errOut+=errs.elementAt(i).toString();
            errOut+="<br>";
        }
        out.println("数据处理结果<br>");
        out.println(strOut);
        //输出结果
        if(errsCount!=0){
            out.println("错误原因<br>");
            out.println(errOut);
            }
        %>
    </body>
</html>

 

            image     image  

例6-7 request对象实例4(requestExample4.jsp)

本例综合演示了20多个方法的使用

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>request对象实例演示</title>
    </head>
    <body>
        <hr>
    <%
       request.setAttribute("Name", "张三");
       request.setAttribute("Password", "123456");
       request.setAttribute("Email", "sanz@163.com");
       request.removeAttribute("Password");
       Enumeration e=request.getAttributeNames();
       String attrName;
            while(e.hasMoreElements()) {
                attrName = e.nextElement().toString();
               out.print(attrName + " = " + request.getAttribute(attrName) + "<br>");
        }
       request.setCharacterEncoding("ISO-8859-1");
     %>
    <%= request.getCharacterEncoding() %>
    Content Length : <%= request.getContentLength() %><br>
    Content Type : <%= request.getContentType() %><br>
    <%= request.getContextPath() %>
    服务器地址:<%= request.getLocalAddr() %><br>
    服务器名称:<%= request.getLocalName() %><br>
    <%= request.getMethod() %>
    <%= request.getProtocol() %><br>
    客户端地址:<%= request.getRemoteAddr()%><br>
    客户端名称:<%= request.getRemoteHost() %><br>
    客户端端口:<%= request.getRemotePort() %><br>
    验证用户名:<%= request.getRemoteUser() %><br>
    获取SessionId<%= request.getRequestedSessionId() %><br>
    请求URI:<%= request.getRequestURI() %><br>
    请求URL:<%= request.getRequestURL() %><br>
    服务器名字:<%= request.getServerName() %><br>
    服务器端口:<%= request.getServerPort() %><br>
    <%= request.getServletPath() %><br>
    <%= request.getSession().getId() %><br>
    请求的会话ID是否通过Cookie传入:<%= request.isRequestedSessionIdFromCookie() %><br>
    请求的会话ID是否通过URL传入:<%= request.isRequestedSessionIdFromURL() %><br>
    请求的会话ID是否仍然有效:<%= request.isRequestedSessionIdValid() %><br>
    <%= request.isSecure() %>
<hr>
</body>
</html>

image                      

6.4 response对象

        response对象实现HttpServletResponse接口,它可以使用 HttpServletResponse的方法将服务器端数据发送到客户端。response对象的生命周期由JSP容器自动控制。当服务

        器向客户端传送数据时,JSP容器就会创建response对象并将请求信息包装到response对象中;当JSP容器处理完请求后,response对象就会被销毁。

response对象包含了响应客户请求的有关信息,它封装了JSP产生的响应,然后被发送到客户端以响应客户的请求。response对象的主要方法如下:

1.addCookie(Cookie cook):用于给用户添加一个Cookie对象,保存客户端的相关信息。可使用request的getCookies()方法获取该Cookie对象。

2.addHeader(String name,String value):用于添加带有指定名称和字符串的HTTP文件头信息,该Header信息将传达到客户端,如果不存在就添加,存在则覆盖。

3.addDateHeader(String name,String value):用于添加带有指定名称和日期值的HTTP文件头信息,该Header信息将传达到客户端,如果不存在就添加,存在则覆盖。

4.containsHeader(String name):用于判断指定名称的Header是否已经存在,存在返回true,否则返回false。

5.flushBuffer():用于强制把当前缓冲区所有内容发送到客户端。

6.getBufferSize():用于获取实际缓冲区的大小,如果没使用缓冲区则返回0。

7.getCharacterEncoding():用于获取响应的字符编码方式。

8.getContentType():用于获取响应的内容MIME类型。

9.getOutputStream():用于获取到客户端的输出流。

10.sendError():用于向客户端发送错误信息。如:404指网页找不到错误。

11.sendRedirect():用于重新定向客户端的请求。

12.setCharacterEncoding():用于设置响应的字符编码方式。

13.setContent():用于设置响应的内容MIME类型。

14.setContentLength():用于设置响应内容的长度(字节数。)

15.setHeader():用于设置指定名称和字符串的HTTP文件头信息,该Header信息将传达到客户端,如果不存在就设置,存在则覆盖。

16.setDateHeader():用于设置指定名称和日期值的HTTP文件头信息,该Header信息将传达到客户端,如果不存在就设置,存在则覆盖。

例6-8 reponse对象实例1(responseExamples1.jsp)

html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>response对象实例演示</title>
    </head>
    <body>
      当前时间是:
      <br>
      <hr>
      <%response.setHeader("refresh","2");%>
      <%out.println(new java.util.Date());%>
      <hr>

    </body>
</html>

image

本例主要是实现对页面定时刷新。

例6-9 response对象实例2(responseExample2.jsp和responseExample3.jsp)

image     image

 

6.5 session对象

    session对象指的是客户端与服务器的一次会话,从客户连到服务器的一个WebApplication开始,直到客户端与服务器断开连接为止。session对象用来保存每个用户的信息,以便跟踪

     每个用户的操作状态。其中,session信息保存在容器里,session的ID保存在客户机的Cookie中。一般情况下,用户首次登录系统时容器会给此用户分配一个唯一的标识的session id

     用于区别其他的用户。当用户退出系统时,这个session就会自动消失。session对象实现HttpSession接口

     当一个用户首次访问服务器上的一个JSP页面时, JSP引擎产生一个session对象,同 时分配一个String类型的ID号, JSP引擎同时将这个ID号发送到用户端,存放在Cookie 中,这

     样session对象和用户之间就建立了一一对应的关系。当用户再访问连接该服务器的其它页面时,不再分配给用户新的Session对象。直到关闭浏览器后,服务器端该用户的 Session

      对象才取消,和用户的对应关系也一并消失。当重新打开浏览器再连接到该服务器时,服务器会为该用户再创建一个新的Session对象。

session对象的主要方法如下:

1.getAttribute(String name):用于获取与指定名字相联系的属性,如果属性不存在,将会返回null。

2.getAttributeNames():用于返回session对象中存储的每一个属性对象,结果集是一个Enumeration类的实例。

3.getCreateTime():用于返回session对象被创建时间,单位为毫秒(千分之一秒)。

4.getId():用于返回Session对象在服务器端的编号。每生成一个session对象,服务器为其分配一个唯一编号,以根据编号来识别session,并且正确地处理某一特定的session及其提供的服务。

5.getLastAccessedTime():用于返回和当前session对象相关的客户端最后发送的请求时间。

6.getMaxInactiveInterval():用于返回session对象的生存时间,单位为秒。

7.setAttribute(String name,java.lang.Object value):用于设定指定名字的属性值,并且把它存储在session对象中。

8.setMaxInactiveInterval(int interval):用于设置session的有效时间,单位为秒。

9.invalidate():用于销毁session对象,使得与其绑定的对象都无效。

10.removeAttribute(String name):用于删除指定的属性(包含属性名、属性值)。如果在有效时间内,用户做出了新的请求,那么服务器就会将其看作一个新的用户,此时,服务器将创建一个新的session,旧的session信息将会丢失。

11.isNew():用于判断目前session是否为新的Session,若是则返回ture,否则返回false。

 

    6.5.2 seesion对象实例

     本例实现的功能是获取页面访问次数,页面每访问一次数值加1

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>session对象实例演示</title>
    </head>
    <body>
       <%
          int number =1000;
          //从session对象获取number
          Object obj = session.getAttribute("number");
           if(obj == null) {
               //设定session对象的变量的值
               session.setAttribute("number",String.valueOf(number));
           }
           else {
                 //取得session对象中的number变量
                 number=Integer.parseInt(obj.toString());
                 //统计页面访问次数
                 number+=1;
                 //设定session对象的number变量值
                 session.setAttribute("number",String.valueOf(number));
               }
       %>
            页面访问次数为: <%=number%>
    </body>
</html>

       image       image

例6-11session对象实例2

<%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.*"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>session对象实例演示</title>
    </head>
    <body>
       <hr>
       session的创建时间是:<%=session.getCreationTime()%>&nbsp<%=new Date(session.getCreationTime())%>
       <br>
       session的Id号:<%=session.getId()%>
       <br>
       客户最近一次访问时间是:<%=session.getLastAccessedTime()%>&nbsp<%=new java.sql. Time(session.getLastAccessedTime())%>
       <br>
       两次请求间隔多长时间session将被取消(ms):<%=session.getMaxInactiveInterval()%>
       <br>
       是否是新创建的session:<%=session.isNew()?"是":"否"%>
        <hr>
    </body>
</html>

           image

例6-12session对象实例2

<%@page contentType="text/html" pageEncoding="UTF-8"import="java.util.*" %>
<!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>session对象实例演示</title>
    </head>
    <body>
       <%
           session.setAttribute("name", "李四");
           session.setAttribute("password", "1008610001");
        %>
        姓名:<%= session.getAttribute("name") %> <br>
        密码:<%= session.getAttribute("password") %><br>
        ID号:<%= session.getId() %><br>
        <%
           session.setMaxInactiveInterval(500);
        %>
        最大有效时间:<%= session.getMaxInactiveInterval() %><br>
        <%
           session.removeAttribute("name");
        %>
         姓名:<%= session.getAttribute("name") %> <br>
         <%
          session.invalidate();
        %>
    </body>
</html>

         image

6.6 PageContext对象

         pageContext对象实现了javax.servlet.jsp.pageContext接口,提供了对JSP页面内使用到的所有对象及名字空间的访问,相当于页面中所有功能的集大成者,提供了对几种页

         面属性的访问,并且允许向其它应用组件转发request对象,或者从其它应用组件包含request对象。它的创建和初始化都是由容器来完成的。

          pageContext对象提供的方法可以处理与JSP容器有关的信息以及其它对象的属性。

pageContext对象的主要方法如下:

1.setAttribute(String name,Object attribute):用于设置指定属性及属性值

2.setAttribute(String name,Object obj,int scope):用于在指定范围内设置属性及属性值

3.getAttribute(String name,int scope) :用于指定范围内获取属性的值

4.getAttribute(String name):用于获取指定属性的值

5.getOut():用于返回当前的out对象

6.getPage():用于返回当前的page对象

7.getRequest():用于返回当前的request对象

8.getResponse():用于返回当前的response对象

9.getSession():用于返回当前页面的session对象

10.getServletConfig():用于返回当前的config对象

11.getException():用于返回当前的exception对象

12.getServletContext():用于返回当前页application对象

13.findAttribute():用于按照页面、请示、会话以及应用程序范围的顺序实现对某个已经命名属性的搜索,寻找一属性,返回其属性值或null

14.forward(java.lang.String relativeUrlPath):用于把页面重定向到另一个页面或者Servlet组件上

15.moveAttribute():用于删除默认页面范围或特定对象范围之中的已命名对象

16.release():用于释放pageContext所占资源

17.include(String relativeUrlPath):用于在当前位置包含另一文件

例6-13 pagecontext对象实例(pagecontextExamples.jsp)

page contentType="text/html" pageEncoding="UTF-8"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>pageContext对象实例演示</title>
    </head>
    <body>
        <%
            request.setAttribute("name", "Java");
            session.setAttribute("name", "C++");
            application.setAttribute("name", "C#");
        %>
        request设定的值:<%=pageContext.getRequest().getAttribute("name")%>
        <br>
        session设定的值:<%=pageContext.getSession().getAttribute("name")%>
        <br>
        application设定的值:<%=pageContext.getServletContext().getAttribute("name")%>
        <br>
    </body>
</html>

image

6.7 config对象

        config对象实现了javax.servlet.ServletConfig接口,是JSP页面通过JSP container进行初始化时被传递的对象。config对象提供对初始化JSP的配置参数的访问。

        config对象用于存放Servlet初始的数据结构信息,Web容器在初始化时,使用config对象向Servlet或JSP页面传送信息。在修改Web服务器处理的变量时,只需修改属性文件的内

         容,不需逐一修改JSP文件。

      config对象的主要方法如下:

      1.ServletContext getServletContext():用于返回Servlet所属的application。

      2.getServletName():用于返回Servlet的名字。

      3.String getInitParameter(String name):用于返回指定初始化参数的值,如果指定的参数不存在则返回null。

      4.Enumeration getInitParameterNames():用于以Enumeration类型返回所有初始化参数的名称,如果没有初始化参数则返回null。

6.8 exception对象

       exception对象实现了java.lang.Throwable接口,用来处理JSP文件在执行时发生的错误和异常。exception对象可以配合page指起使

       用,在page指令中isErrorPage属性应设为true,否则无法编译。

       通过exception对象的方法指定某一个页面为错误处理页面,把所有的错误都集中该页面进行处理,可以使得整个系统的健壮性得到加

       强,也使得程序的流程更加简单明晰。

      6.8.1 exception对象方法

              exception对象的主要方法如下:

              1.getMessage():用于返回描述异常错误的提示信息。

              2.getlocalizedMessage():用于获取本地化错误信息。

              3.printStackTrace():用于输出异常对象及其堆栈跟踪信息。

              4.toString():返回关于异常的简短描述消息。

       6.8.2 execption对象实例

               例6-15 exception对象实例1(exceptionExample1.jsp)

          %@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>exception对象实例演示</title>
    </head>
    <body>
       <% int x = 6, y = 0, z;
           try { z = x / y;
            }
          catch(Exception e) { out.println(e.toString()+"<br>"); }
          finally {
              out.println("产生了除以0的错误!");
          }
        %>
    </body>
</html>

例6-16 exception对象实例2(exceptionExample2.jsp和error.jsp)

本例使用了getLocalizedMessage()方法、getMessager()方法和tostring()方法,包括两个文件:其中error.jsp产生导异常,exceptionexamplele2.jsp进行异常处理

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page errorPage="exceptionExamples2.jsp" %>
<!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>exception对象实例演示</title>
    </head>
    <body>
    <%= (6 /0) %>
    </body>
</html>

exceptionexamplele2.jsp


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>exception对象实例演示</title>
    </head>
    <body>
        <%= exception.getLocalizedMessage()  %>
        <%= exception.getMessage()  %>
        <%=exception.toString()%>
    </body>
</html>

 

 

6.9 application对象

       application对象实现了ServletContext类和接口,并保存Web应用程序中公有的数据,可存放全局变量。服务器启动后自动创建application对象,此对象将一直有效,直到服务器

        关闭。不同用户可以对该对象的同一属性进行操作;在任何地方对此对象属性的操作,都将影响到其他用户对此对象的访问。

       application对象和session对象的区别是:在使用session对象时,各个客户端共享一个session对象,而使用Application对象时,为多个应用程序保存信息,对于一个容器而言,

       在同一个服务器中的JSP文件中共享一个application对象

       application对象的主要方法如下:

          1.getAttribute(String name):用于返回给定application对象的属性的值

          2.getAttributeNames():用于以Enumeration类型返回application对象的某个属性的初始值

          3.getServerInfo():用于返回servlet编译器的当前版本信息

          4.getContext(String uripath):用于返回指定WebApplication的application对象

          5.getMimeType(String file):用于返回application对象指定文件的MIME类型

          6.getResource(String path):用于返回application对象指定资源(文件及目录)的URL路径

          7.getServlet(String name):用于返回application对象指定的Servlet

          8.setAttribute(String name,Object obj):用于设定application对象的属性及其属性值

          9.removeAttribute(String name):用于删除application对象属性及其属性值

           10.log(String msg):用于指定application对象消息写入Servlet的日志文件

   例6-17 application对象实例(applicationExample1.jsp)


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>application对象实例演示</title>
    </head>
    <body>
        <br>
        JSP引擎名及Servlet版本号:<%=application.getServerInfo()%><br>
        <%
           application.setAttribute("name","Java");
           out.print(application.getAttribute("name")+"<br>");
           application.removeAttribute("name");
           out.print(application.getAttribute("name")+"<br>");
        %>

    </body>
</html>

image

    例6-18 application对象实例2(applicationExample2.jsp)

    本例是一个页面访问次数所计数器,每访问一次页面计数器值增1
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>application对象实例演示</title>
    </head>
    <body>
        <%
        //获取一个Object对象
          String strNum = (String)application.getAttribute("count");
          int count = 0;
          //如果一个Object对象存在说明有用户访问
          if(strNum != null)
              //类型转化后值加1
             count = Integer.parseInt(strNum) + 1;
          //人数值加1后重新对count赋值
          application.setAttribute("count", String.valueOf(count));
         %>
         您是第<%=application.getAttribute("count")%>位访问者
    </body>
</html>

image

posted @ 2014-02-22 13:13  elite_2012  阅读(352)  评论(0编辑  收藏  举报