zoukankan      html  css  js  c++  java
  • JSP_3_JSP内置对象

    ,---3-1 JSP内置对象简介---------------------------------------------------------------------------------------

    JSP内置对象是Web容器创建的一组对象,不实用new关键字就可以使用的内置对象

    <%

      int[] value ={60,70,80};

      for(int i:value){

        out.println(i);

      }

    %>

    JSP脚本中包含了9个内置对象,这9个内置对象都是Servlet API接口的实例(可以直接使用)。

      JSP内置对象的实质:他们要么是_jspService()方法的形参,要么是_jspService()方法的局部变量,所以在

    JSP脚本中调用这些对象,无须创建它们。

    常   用:5个。out,request,response,session,application。

    不常用:Page,pageContext,execption,config。

    ---3-2 Web程序的请求与相应模式---------------------------------------------------------------------------------------

    ·Web程序的请求与相应模式

      用户发送请求(request)

      服务器给用户相应(response)

    ---3-4 out对象---------------------------------------------------------------------------------------

    1.缓冲区

    缓冲区:Buffer,所谓缓冲区就是内存的一块区域用来保存临时数据。

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>四种作用域范围</h1>
    25     Application:<%=PageContext.APPLICATION_SCOPE %><BR>
    26     Session:<%=PageContext.SESSION_SCOPE %><br>
    27     Request:<%=PageContext.REQUEST_SCOPE %><br>
    28     Page:<%=PageContext.PAGE_SCOPE %><br>
    29   </body>
    30 </html>

    2.out对象是JspWriter类的实例,是向客户端输出内容常用的对象。

      代表一个页面的输出流,通常用于在页面上输出变量值及常量。

    常用方法如下:

      1)void println() 向客户端打印字符串。

      2)void clear()清除缓冲区的内容,如果在flush之后调用会抛出异常。

      3)void clearBuffer()清除缓冲区的内容,如果在flush之后调用不会抛出异常。

      4)void flush()将缓冲区的内容输出到客户端。

      5)int getBufferSize()返回缓冲区以字节数的大小,如不设缓冲区则为0。

      6)int getRemaining()返回缓冲区还剩余多少可用。

      7)boolean isAutoFlush()返回缓冲区满时,是自动清空还是跑出异常。

      8)void close()关闭输出流。

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>out内置对象</h1>
    25     <% 
    26        out.println("<h2>静夜思</h2>");
    27        out.println("床前明月光<br>");
    28        out.println("疑是地上霜<br>");
    29        out.flush();
    30        //out.clear();//这里会抛出异常。
    31        out.clearBuffer();//这里不会抛出异常。
    32        out.println("举头望明月<br>");
    33        out.println("低头思故乡<br>");
    34     
    35     %>
    36         缓冲区大小:<%=out.getBufferSize() %>byte<br>
    37         缓冲区剩余大小:<%=out.getRemaining() %>byte<br>
    38        是否自动清空缓冲区:<%=out.isAutoFlush() %><BR>    
    39   </body>
    40 </html>

    ---3-6 get与post提交方式的区别---------------------------------------------------------------------------------------

    get与post的区别

    <form name="regForm" action="动作" method="提交方式">

    </form>

    1.get 以明文的方式通过URL提交数据,数据在URL中可见。提交的数据最多不超过2KB。安全性低但效率比POST方式高。

    适合提交数据量不大,安全性不高的数据。比如:搜索,查询功能

    2.post:将提交信息封装在HTML HEADER内(POST把提交的数据则放置在是HTTP包的包体中)。适合提交数据量大,安全性高的用户信息。比如:注册,修改,上传等功能。

    提交页:colspan="2"夸列的效果method先后设置get和post观察

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'login.jsp' starting page</title>
    13     
    14     <meta http-equiv="pragma" content="no-cache">
    15     <meta http-equiv="cache-control" content="no-cache">
    16     <meta http-equiv="expires" content="0">    
    17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    18     <meta http-equiv="description" content="This is my page">
    19     <!--
    20     <link rel="stylesheet" type="text/css" href="styles.css">
    21     -->
    22 
    23   </head>
    24   
    25   <body>
    26     <h1>用户登录</h1>
    27     <hr>
    28     <form action="dologin.jsp" name="loginForm" method="post">
    29      <table>
    30        <tr>
    31          <td>用户名:</td>
    32          <td><input type="text" name="username"/></td>
    33        </tr>
    34        <tr>
    35          <td>密码:</td>
    36          <td><input type="password" name="password"/></td>
    37        </tr>
    38        <tr>
    39          <td colspan="2"><input  type="submit" value="登录"></td>
    40        </tr>
    41      </table>
    42     </form>
    43   </body>
    44 </html>

    action:dologin

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'dologin.jsp' starting page</title>
    13     
    14     <meta http-equiv="pragma" content="no-cache">
    15     <meta http-equiv="cache-control" content="no-cache">
    16     <meta http-equiv="expires" content="0">    
    17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    18     <meta http-equiv="description" content="This is my page">
    19     <!--
    20     <link rel="stylesheet" type="text/css" href="styles.css">
    21     -->
    22 
    23   </head>
    24   
    25   <body>
    26     <h1>登录成功</h1>
    27     <hr>
    28   </body>
    29 </html>

    ---3-7 request对象---------------------------------------------------------------------------------------

    每一个request对象封装着一次用户的请求,并且所有的请求参数都被封装在request对象中,因此request对象是获取

    请求参数的重要途径。是HttpServletRequest类的实例(instance)。request对象具有请求域,即完成客户端的请求之前,该对象一直有效。

    常用方法:

      1)String getParameter(String paramName) :获取paramName请求参数的值。

      2) String[] getParameterValues(String name) :paramName请求参数的值,当参数有多个值的时候,该参数方法返回多个参数值。

      3) void setAttribute(String,Object):存储此请求中的属性

      4) object getAttribute(String name):返回指定属性的属性值

      5)String getContentType():得到请求体的MIME类型

      6)String getProtocol():返回请求用的协议类型及版本号

      7)String getServerName():返回接受请求的服务器主机名 

      >Map getParameterMap() : 获取所有请求参数名和参数值组成Map对象。

      >Enumeration getParameterNames() :获取所有请求参数名所组成的Enumeration对象。

      HttpServletRequest提供了如下方法来访问请求头:

      >String getHeader(String name):根据指定请求头的值。

      >Enumeration<STring> getHearderNames() :获取所有请求头的名称。

      >Enumeration<STring> getHearders(String name) :获取请求头的多个值。

      >int getIntHeader(String name):获取指定请求头的值,并将该值转化为整数值。

    reg.jsp

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>用户注册</h1>
    25     <hr>
    26     <% 
    27        int number=-1;
    28        //说明用户第一次访问页面,计数器对象还未创建
    29        if(application.getAttribute("counter")==null)
    30        {
    31            application.setAttribute("counter", 0);
    32        }
    33        number = Integer.parseInt(application.getAttribute("counter").toString());
    34        number++;
    35        application.setAttribute("counter", number);
    36     %>
    37     <!-- <form name="regForm" action="request.jsp" method="post"> -->
    38     <form name="regForm" action="request.jsp" method="post">
    39     <table>
    40       <tr>
    41         <td>用户名:</td>
    42         <td><input type="text" name="username"/></td>
    43       </tr>
    44       <tr>
    45         <td>爱好:</td>
    46         <td>
    47            <input type="checkbox" name="favorite" value="read">读书
    48            <input type="checkbox" name="favorite" value="music">音乐
    49            <input type="checkbox" name="favorite" value="movie">电影
    50            <input type="checkbox" name="favorite" value="internet">上网
    51         </td>
    52       </tr>
    53       <tr>
    54          <td colspan="2"><input type="submit" value="提交"/></td>
    55       </tr>
    56     </table>
    57     </form>
    58     <br>
    59     <br>
    60     <a href="request.jsp?username=李四">测试URL传参数</a>
    61     
    62     <br>
    63     <br>
    64     <center>
    65              您是第<%=number %>位访问本页面的用户。
    66     </center>
    67   </body>
    68 </html>

    request.jsp:

    request.setCharacterEncoding("utf-8");设置请求默认字符集(默认为ISO8859-11)与提交页面字符集相同

    if(request.getParameterValues("favorite")!=null)//通过url传参时,空指针判断。request.setCharacterEncoding("utf-8");无法解决此中文乱码。解决方法为配置tomcat服务器的server.xml
    //<Connector ...ridirectPort="8443" URIEncoding="utf-8"/> 修改后一定重启服务器

    Eclipse的看过来。当你在conf下的service.xml中修改不管用的时候,你打开你的eclipse的工作空间,下面有个service打开里面的service.xml进行添加URIEncoding="utf-8"就好了

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>request内置对象</h1>
    25     <% 
    26        request.setCharacterEncoding("utf-8"); //解决中文乱码问题,无法解决URL传递中文出现的乱码问题。
    27        request.setAttribute("password", "123456");
    28     
    29     %>
    30         用户名:<%=request.getParameter("username") %><br>   
    31         爱好 :<% 
    32            if(request.getParameterValues("favorite")!=null)//通过url传参时,空指针判断。request.setCharacterEncoding("utf-8");无法解决此中文乱码。解决方法为配置tomcat服务器的server.xml
    //<Connector ...ridirectPort="8443" URIEncoding="utf-8"/> 修改后一定重启服务器
    33 { 34 String[] favorites = request.getParameterValues("favorite"); 35 for(int i=0;i<favorites.length;i++) 36 { 37 out.println(favorites[i]+"&nbsp;&nbsp;"); 38 } 39 } 40 %> <br> 41 密码:<%=request.getAttribute("password") %><br> 42 请求体的MIME类型:<%=request.getContentType() %><br> 43 协议类型及版本号: <%=request.getProtocol() %><br> 44 服务器主机名 :<%=request.getServerName() %><br> 45 服务器端口号:<%=request.getServerPort() %><BR> 46 请求文件的长度 :<%=request.getContentLength() %><BR> 47 请求客户端的IP地址:<%=request.getRemoteAddr() %><BR> 48 请求的真实路径:<%=request.getRealPath("request.jsp") %><br> 49 请求的上下文路径:<%=request.getContextPath() %><BR> 50 51 52 53 </body> 54 </html>

    ---3-10 response对象---------------------------------------------------------------------------------------

    response对象包含了相应客户请求的有关信息,但是在JSP中很少直接用到它。它是HttpServletResponse类的实例。response对象response对象具有页面作用域,即访问一个页面时,该页面内的response对象response对象只能对这次访问有效,其他页面的response对象对当前页面无效。

    常用方法:

    1)String getCharacterEncoding()返回响应用的是何种字符编码

    2)void setContentType(String type)设置响应的MIME类型

    3)PrintWriter getWriter()返回可以向客户端输出字符的一个对象(注意比较:PrintWriter与内置对象out对象的区别)

    4)sendRedirect(java.lang.String location)重新定向客户端的请求

    response:

    <%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%>

    import多个包时,在""内用","隔开

     1 <%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3     response.setContentType("text/html;charset=utf-8"); //设置响应的MIMI类型
     4     
     5     out.println("<h1>response内置对象</h1>");
     6     out.println("<hr>");
     7     //out.flush();
     8     
     9     PrintWriter outer = response.getWriter(); //获得输出流对象
    10     outer.println("大家好,我是response对象生成的输出流outer对象");
    11     //response.sendRedirect("reg.jsp");//请求重定向
    12     //请求重定向
    13     //response.sendRedirect("request.jsp");
    14     //请求转发
    15     request.getRequestDispatcher("request.jsp").forward(request, response);
    16 %>

     结果:

    1 输出结果:PrintWriter打印内容提前于内置的out对象。

    用flush()方法可以使out对象先打印

         out.println("<h1>response内置对象</h1>");

         out.println("<hr>");

      out.flush();
         
         PrintWriter outer = response.getWriter(); //获得输出流对象
         outer.println("大家好,我是response对象生成的输出流outer对象");

    2 重定向

      //请求重定向 

         response.sendRedirect("request.jsp");//跳转到request.jsp页面

    ---3-11 请求重定向与请求转发的区别--------------------------------------------------------------------------

    请求重定向与请求转发

      请求重定向:客户端行为,response.sendRedirect(),从本质上讲等同于两次请求,前翼子请求的对象不会保存,地址栏的URL地址会改变。

      请求转发:服务器行为,request.getRequestDispatcher().forward(req,resp);是一次请求,转发后请求对象会保存,地址栏的URL地址不会改变。

    reg.jsp

     
     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     7 <html>
     8   <head>
     9     <base href="<%=basePath%>">
    10     
    11     <title>My JSP 'index.jsp' starting page</title>
    12  <meta http-equiv="pragma" content="no-cache">
    13  <meta http-equiv="cache-control" content="no-cache">
    14  <meta http-equiv="expires" content="0">    
    15  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    16  <meta http-equiv="description" content="This is my page">
    17  <!--
    18  <link rel="stylesheet" type="text/css" href="styles.css">
    19  -->
    20   </head>
    21   
    22   <body>
    23     <h1>用户注册</h1>
    24     <hr>
    25     <% 
    26        int number=-1;
    27        //说明用户第一次访问页面,计数器对象还未创建
    28        if(application.getAttribute("counter")==null)
    29        {
    30            application.setAttribute("counter", 0);
    31        }
    32        number = Integer.parseInt(application.getAttribute("counter").toString());
    33        number++;
    34        application.setAttribute("counter", number);
    35     %>
    36     <!-- <form name="regForm" action="request.jsp" method="post"> -->
    37     <form name="regForm" action="response.jsp" method="post">
    38     <table>
    39       <tr>
    40         <td>用户名:</td>
    41         <td><input type="text" name="username"/></td>
    42       </tr>
    43       <tr>
    44         <td>爱好:</td>
    45         <td>
    46            <input type="checkbox" name="favorite" value="read">读书
    47            <input type="checkbox" name="favorite" value="music">音乐
    48            <input type="checkbox" name="favorite" value="movie">电影
    49            <input type="checkbox" name="favorite" value="internet">上网
    50         </td>
    51       </tr>
    52       <tr>
    53          <td colspan="2"><input type="submit" value="提交"/></td>
    54       </tr>
    55     </table>
    56     </form>
    57     <br>
    58     <br>
    59     <a href="request.jsp?username=李四">测试URL传参数</a>
    60     
    61     <br>
    62     <br>
    63     <center>
    64              您是第<%=number %>位访问本页面的用户。
    65     </center>
    66   </body>
    67 </html>

    response.jsp

    <%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%>
    <%
        response.setContentType("text/html;charset=utf-8"); //设置响应的MIMI类型
        
        out.println("<h1>response内置对象</h1>");
        out.println("<hr>");
        //out.flush();
        
        PrintWriter outer = response.getWriter(); //获得输出流对象
        outer.println("大家好,我是response对象生成的输出流outer对象");
        //response.sendRedirect("reg.jsp");//请求重定向
        //请求重定向
        //response.sendRedirect("request.jsp");
        //请求转发
        request.getRequestDispatcher("request.jsp").forward(request, response);
    %>

    ---4-1 什么是session---------------------------------------------------------------------------------------

    ·session:表示客户端与服务器的一次会话

    ·Web中的session指的是用户在浏览某个网站时,从进入发网站到浏览器关闭所经过的这段时间,也就是用户浏览这个网站所花费的时间

      从以上可见,session实际上是一个特定的时间概念

    ·在服务器内存中保存着不同用户的session,和用户一一对应。

    ---4-2 session对象---------------------------------------------------------------------------------------

    ·session对象是一个JSP内置对象。

    ·session对象在第一个jsp页面被装载时自动创建,完成会话期管理。

    ·当客户端浏览器与站点建立连接时,会话开始;当客户端关闭浏览器时,会话结束。

    ·当一个客户访问服务器时,可能会在服务器几个页面之间切换,服务器应当通过某种办法知道这是一个用户,就需要session对象。

    ·session是javax.servlet.http.HttpSession 的实例 。

      session通常用于跟踪用户的会话信息,session范围内的属性可以在多个页面的跳转之间共存。

    常用方法:

    > long getCreationTime():返回session创建时间

    > public String getId():返回session创建时JSP引擎为它设置的唯一ID号

    > public Object setAttribute(String Name , Object Value) :使用指定名称将对象绑定至此对话。设置session 范围内attName属性的值为attValue 。

    > public Object getAttribute(String attName):返回与此绘画中的指定名称绑定在一起的对象,如果没有对象绑定在该名称下,则返回null。返回session范围内attName属性的值。

    > String[] getValueNames():返回一个包含此SESSION中所有可用属性的数组

    > int getMaxInactiveInterval():返回两次请求间隔多长时间此Session被取消(单位秒)

     sessionpage1:

    <a href="session_page2.jsp"  target="_blank" >跳转到Session_page2.jsp</a>新窗口打开

    <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=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>
        <h1>session内置对象</h1>
        <hr>
        <% 
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
          Date d = new Date(session.getCreationTime());
          session.setAttribute("username", "admin"); 
          session.setAttribute("password", "123456");
          session.setAttribute("age", 20);
          
          //设置当前session最大生成期限单位是秒
          //session.setMaxInactiveInterval(10);//10秒钟
          //session.invalidate();//销毁当前会话。
        %>
         
        Session创建时间:<%=sdf.format(d)%><br>    
        Session的ID编号:<%=session.getId()%><BR>
             从Session中获取用户名:<%=session.getAttribute("username") %><br>
        <% 
           //session.invalidate();//销毁当前会话
        %>
        <a href="session_page2.jsp" target="_blank">跳转到Session_page2.jsp</a>     
            
      </body>
    </html>

      sessionpage2:

    测试session是否是同一个

    <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=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>
        <h1>session内置对象</h1>
        <hr>
        <% 
          //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
          //Date d = new Date(session.getCreationTime());
          //session.setAttribute("username", "admin"); 
        %>
            
        Session的ID编号:<%=session.getId()%><BR>
             从Session中获取用户名:<%=session.getAttribute("username") %><br>
        Session中保存的属性有:<% 
                         String[] names =session.getValueNames();
                         for(int i=0;i<names.length;i++)
                         {
                            out.println(names[i]+"&nbsp;&nbsp;");
                         }
        
        %> <br>    
      </body>
    </html>

    ---4-4 session生命周期---------------------------------------------------------------------------------------

    创建:

      当客户端第一次访问JSP或者Servlet时,服务器会为当前回话创建一个SessionID,每次客户端向服务器发送请求时,都会将此SessionID携带过去,服务端会对此SessionID进行校验。

    活动:

      1)某次会话当中通过超链接打开的新页面属于同一次会话。

      2)只要当前会话页面没有全部关闭,重新打开的新浏览器窗口访问同一项目资源时属于同一次会话。

      3)除非本次会划所有页面都关闭后再重新访问某个JSP或者Servlet将会创建新会话。

        注意:注意原有会话还存在,只是这个旧的SessionID仍然存在于服务端,只不过再也没有客户端会携带它然后交于服务端校验。

    销毁:

      Session的销毁只有三种方式:

      1.调用session.invalidate()方法

      2.Session过期(timeout)

      3.服务器重启

    sessionpage1:验证活动的1)2)3)

     1 <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>session内置对象</h1>
    25     <hr>
    26     <% 
    27       SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    28       Date d = new Date(session.getCreationTime());
    29       session.setAttribute("username", "admin"); 
    30       session.setAttribute("password", "123456");
    31       session.setAttribute("age", 20);
    32       
    33       //设置当前session最大生成期限单位是秒
    34       //session.setMaxInactiveInterval(10);//10秒钟
    35       //session.invalidate();//销毁当前会话。
    36     %>
    37      
    38     Session创建时间:<%=sdf.format(d)%><br>    
    39     Session的ID编号:<%=session.getId()%><BR>
    40          从Session中获取用户名:<%=session.getAttribute("username") %><br>
    41     <% 
    42        //session.invalidate();//销毁当前会话
    43     %>
    44     <a href="session_page2.jsp" target="_blank">跳转到Session_page2.jsp</a>     
    45         
    46   </body>
    47 </html>

    sessionpage2:

    <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=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>
        <h1>session内置对象</h1>
        <hr>
        <% 
          //SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
          //Date d = new Date(session.getCreationTime());
          //session.setAttribute("username", "admin"); 
        %>
            
        Session的ID编号:<%=session.getId()%><BR>
             从Session中获取用户名:<%=session.getAttribute("username") %><br>
        Session中保存的属性有:<% 
                         String[] names =session.getValueNames();
                         for(int i=0;i<names.length;i++)
                         {
                            out.println(names[i]+"&nbsp;&nbsp;");
                         }
        
        %> <br>    
      </body>
    </html>

     Session对象

      Tomcat默认session超时时间为30分钟

      设置session超时有两种方式:

      1.session.setMaxInactiveInterval(time)//秒单位

      2.在web.xml配置

        <session-config>

          <session-timeout>10</session-timeout>

        </session-config>//分钟单位

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app version="2.5" 
     3     xmlns="http://java.sun.com/xml/ns/javaee" 
     4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
     6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     7   <display-name></display-name>    
     8   <welcome-file-list>
     9     <welcome-file>index.jsp</welcome-file>
    10   </welcome-file-list>
    11   <!-- 设置会话一分钟后过期 -->
    12   <session-config>
    13     <session-timeout>1</session-timeout>
    14   </session-config>
    15 </web-app>

    ---4-6 application对象---------------------------------------------------------------------------------------

    application对象:

    ·application对象实现了用户间数据的共享,可存放全局变量。

    application开始于服务器的启动,终止于服务器的关闭。

    在用户的前后连接或不同用户之间的连接中,可以对application对象的同一属性进行操作。

    在任意一个地方对application对象属性的操作,都将影响到其他用户对此的访问。

    服务器的启动和关闭决定了application对象的生命。

    application对象是ServeltContext类的实例。

    常用方法:

    > public Object setAttribute(String Name , Object Value) :使用指定名称将对象绑定至此对话。

    > public Object getAttribute(String attName):返回与此绘画中的指定名称绑定在一起的对象,如果没有对象绑定在该名称下,则返回null。

    Enumeration getAttributeNames():返回所有可用属性的枚举

    String getServerInfo()返回JSP(SERVELT)引擎名及版本号

    application:

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>application内置对象</h1>
    25     <% 
    26        application.setAttribute("city", "北京");
    27        application.setAttribute("postcode", "10000");
    28        application.setAttribute("email", "lisi@126.com");
    29        
    30     %>
    31          所在城市是:<%=application.getAttribute("city") %><br>
    32     application中的属性有:<% 
    33          Enumeration attributes = application.getAttributeNames();
    34          while(attributes.hasMoreElements())
    35          {
    36             out.println(attributes.nextElement()+"&nbsp;&nbsp;");
    37          }
    38     %><br>
    39     JSP(SERVLET)引擎名及版本号:<%=application.getServerInfo() %><br>              
    40                    
    41   </body>
    42 </html>

    ---4-8 page对象---------------------------------------------------------------------------------------

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

    常用方法如下:
    1 class getClass 返回此Object的类 
    2 int hashCode() 返回此Object的hash码 
    3 boolean equals(Object obj) 判断此Object是否与指定的Object对象相等 
    4 void copy(Object obj) 把此Object拷贝到指定的Object对象中 
    5 Object clone() 克隆此Object对象 
    6 String toString() 把此Object对象转换成String类的对象 
    7 void notify() 唤醒一个等待的线程 
    8 void notifyAll() 唤醒所有等待的线程 
    9 void wait(int timeout) 使一个线程处于等待直到timeout结束或被唤醒 
    10 void wait() 使一个线程处于等待直到被唤醒 
    11 void enterMonitor() 对Object加锁 
    12 void exitMonitor() 对Object开锁

    演示toString方法:

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>page内置对象</h1>
    25     
    26          当前page页面对象的字符串描述:<%=page.toString() %><br> 
    27               
    28                    
    29   </body>
    30 </html>

    ---4-9 pageContext对象和config对象---------------------------------------------------------------------------------------

    pageContext对象提供了对JSP页面内所有的对象及名字空间的访问,

    pageContext对象可以访问到本页所在的SESSION,也可以取本页面所在的application的某一属性值

    pageContext对象相当于页面中所有功能的集大成者

    pageContext对象的本类名也叫pageContext。 

    常用方法
    1 JspWriter getOut() 返回当前客户端响应被使用的JspWriter流(out) 
    2 HttpSession getSession() 返回当前页中的HttpSession对象(session) 
    3 Object getPage() 返回当前页的Object对象(page) 
    4 ServletRequest getRequest() 返回当前页的ServletRequest对象(request) 
    5 ServletResponse getResponse() 返回当前页的ServletResponse对象(response) 
    6 Exception getException() 返回当前页的Exception对象(exception) 
    7 ServletConfig getServletConfig() 返回当前页的ServletConfig对象(config) 
    8 ServletContext getServletContext() 返回当前页的ServletContext对象(application) 
    9 void setAttribute(String name,Object attribute) 设置属性及属性值 
    10 void setAttribute(String name,Object obj,int scope) 在指定范围内设置属性及属性值 
    11 public Object getAttribute(String name) 取属性的值 
    12 Object getAttribute(String name,int scope) 在指定范围内取属性的值 
    13 public Object findAttribute(String name) 寻找一属性,返回起属性值或NULL 
    14 void removeAttribute(String name) 删除某属性 
    15 void removeAttribute(String name,int scope) 在指定范围删除某属性 
    16 int getAttributeScope(String name) 返回某属性的作用范围 
    17 Enumeration getAttributeNamesInScope(int scope) 返回指定范围内可用的属性名枚举 
    18 void release() 释放pageContext所占用的资源 
    19 void forward(String relativeUrlPath) 使当前页面重导到另一页面 
    20 void include(String relativeUrlPath) 在当前位置包含另一文件 

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>pageContext内置对象</h1>
    25     <hr>    
    26         用户名是:<%=pageContext.getSession().getAttribute("username") %><br>      
    27     <% 
    28        //跳转到注册页面
    29        //pageContext.forward("reg.jsp");
    30        pageContext.include("include.jsp");
    31     %>                
    32   </body>
    33 </html>

     include.jsp:

    <%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
    <%
     String path = request.getContextPath();
     String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     Date date = new Date();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
     String s = sdf.format(date);
     out.println(s+"<br>");
    %>

    9.config对象  servlet中详细介绍
    config对象是在一个Servlet初始化时,JSP引擎向它传递信息用的,此信息包括Servlet初始化时所要用到的参数(通过属性名和属性值构成)以及服务器的有关信息(通过传递一个ServletContext对象) 


    1 ServletContext getServletContext() 返回含有服务器相关信息的ServletContext对象 
    2 String getInitParameter(String name) 返回初始化参数的值 
    3 Enumeration getInitParameterNames() 返回Servlet初始化所需所有参数的枚举

    ---4-10 exception对象---------------------------------------------------------------------------------------

     exception对象 
    exception对象是一个例外对象,当一个页面在运行过程中发生了例外,就产生这个对象。如果一个JSP页面要应用此对象,就必须把isErrorPage设为true,否则无法编译。他实际上是java.lang.Throwable的对象 


    1 String getMessage() 返回描述异常的消息 
    2 String toString() 返回关于异常的简短描述消息 
    3 void printStackTrace() 显示异常及其栈轨迹 
    4 Throwable FillInStackTrace() 重写异常的执行栈轨迹 

    exception.jsp:

     <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" isErrorPage="true" %>isErrorPage="true

    <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" isErrorPage="true" %>
    <%
    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>
        <h1>exception内置对象</h1>
        <hr>
        
            异常的消息是:<%=exception.getMessage()%><BR>
            异常的字符串描述:<%=exception.toString()%><br>
      </body>
    </html>

    exception_test.jsp:

    <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" errorPage="exception.jsp"%> 异常信息交给exception.jsp处理

     1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" errorPage="exception.jsp"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">    
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21   </head>
    22   
    23   <body>
    24     <h1>测试异常的页面</h1>
    25     <hr>
    26     
    27     <% 
    28       System.out.println(100/0); //抛出运行时异常,算数异常
    29     %>
    30   </body>
    31 </html>
  • 相关阅读:
    Mac Mysql 修改初始化密码
    网址收藏
    Xcode 模拟器复制解决方案
    ios优秀的第三方框架
    CocoaPods第三方库管理工具
    ios网络请求
    java面试宝典
    SQL分表
    FastDFS+Nginx+Module
    分布式文件系统FastDFS架构认知
  • 原文地址:https://www.cnblogs.com/charles999/p/6688242.html
Copyright © 2011-2022 走看看